I have an array of JSON
'[
{"key": "cId", "value": "d03ce656"},
{"key": "cName", "value": "Healthcare"},
{"key": "pId", "value": "d869628b"},
{"key": "pName", "value": "ConveYour"}
]
I want to convert it to
{
"cId": "d03ce656",
"cName": "Healthcare",
"pId" : "d869628b",
"pName": "ConveYour"
}
so far I have tried
SELECT
OBJECT_CONSTRUCT(
parse_json(f.value):key::string,
parse_json(f.value):value::string
) AS json_object
FROM LATERAL FLATTEN(INPUT => PARSE_JSON('[
{"key": "cId", "value": "d03ce656"},
{"key": "cName", "value": "Healthcare"},
{"key": "pId", "value": "d869628b"},
{"key": "pName", "value": "ConveYour"}
]')) AS f;
but it gives me
JSON_OBJECT
{ "cId": "d03ce656" }
{ "cName": "Healthcare" }
{ "pId": "d869628b" }
{ "pName": "ConveYour" }
I do not want 4 rows but one element { "cId": "d03ce656", "cName": "Healthcare", "pId" : "d869628b", "pName": "ConveYour" }
You need to use the aggregate function OBJECT_AGG()
:
SELECT OBJECT_AGG(
parse_json(f.value):key,
parse_json(f.value):value
) AS json_object
FROM LATERAL FLATTEN(INPUT => PARSE_JSON('[
{"key": "cId", "value": "d03ce656"},
{"key": "cName", "value": "Healthcare"},
{"key": "pId", "value": "d869628b"},
{"key": "pName", "value": "ConveYour"}
]')) AS f
GROUP BY f.this;
Results :
JSON_OBJECT
{ "cId": "d03ce656", "cName": "Healthcare", "pId": "d869628b", "pName": "ConveYour" }