WITH key_value AS
(
SELECT e
FROM headers
CROSS JOIN UNNEST(CAST(json_parse(headers) AS array(json))) t(e)
)
SELECT
CAST(JSON_PARSE(e) AS map(varchar, varchar)) AS value
FROM
key_value
{
"headers": [{
"key": "Name",
"value": "xxxx"
},
{
"key": "Email",
"value": "xxxx"
},
{
"key": "ID",
"value": "1234"
},
{
"key": "Company",
"value": "XYZ"
},
{
"key": "Groups",
"value": "[]"
},
{
"key": "Address",
"value": "xxxx"
},
{
"key": "State",
"value": "Log In"
},
{
"key": "Component",
"value": "xxxx"
},
{
"key": "LastUsed",
"value": "xxxx"
}]
}
So far I have tried this code, the first part seems to work which seems to give me the innest JSON objects but can convert them to individual column objects.
I need to turn each headers array into a row with key as column and values as data.
2
Answers
Above query worked for me, first select unnests all JSON key value pairs into individual rows, second select just select the Key and Value as data and the third select pivots each ID into a single row based on Key value.
You can apply second
unnest
(notice succinct syntax) to the map which flattens data into to columns: