简体   繁体   English

雪花 SQL 中的 JSON 解析

[英]JSON Parse in Snowflake SQL

I'm trying to convert the original json to the desired results below using SQL in Snowflake.我正在尝试使用雪花中的 SQL 将原始 json 转换为以下所需的结果。 How can I accomplish this?我怎样才能做到这一点?

I've tried parse_json(newFutureAllocations[0]:fundId) but this only brings back the first fundId element.我试过 parse_json(newFutureAllocations[0]:fundId) 但这只会带回第一个 fundId 元素。

ORIGINAL "newFutureAllocations": [ { "fundId": 1, "percentAllocation": 2500 }, { "fundId": 5, "percentAllocation": 7500 } ]原始“newFutureAllocations”:[{“fundId”:1,“percentAllocation”:2500},{“fundId”:5,“percentAllocation”:7500}]

DESIRED "newFutureAllocations": { "1": 2500, "5": 7500 }所需的“新未来分配”:{“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.您需要使用flatten将数组元素转换为行,然后使用object_agg()将它们再次聚合,作为对象而不是数组。 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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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