Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Snowflake data flattening

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
}

>Solution :

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" }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading