简体   繁体   中英

JSON Parse in Snowflake SQL

I'm trying to convert the original json to the desired results below using SQL in Snowflake. How can I accomplish this?

I've tried parse_json(newFutureAllocations[0]:fundId) but this only brings back the first fundId element.

ORIGINAL "newFutureAllocations": [ { "fundId": 1, "percentAllocation": 2500 }, { "fundId": 5, "percentAllocation": 7500 } ]

DESIRED "newFutureAllocations": { "1": 2500, "5": 7500 }

You need to use flatten to turn your array elements in to rows, then use object_agg() to aggregate them back up again, as an object rather than an array. The exact syntax depends on the rest of your query, data, etc, and you haven't provided enough details about that.

The challenge here is to re-construct the object, I used string concatenations:

with data as (
select parse_json(
    '[ { "fundId": 1, "percentAllocation": 2500 }
    , { "fundId": 5, "percentAllocation": 7500 } ]') j
)

select parse_json('{'||
  listagg('"'||x.value:fundId ||'"'||':'|| x.value:percentAllocation, ',')
  ||'}')
from data, table(flatten(j)) x
group by seq

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM