从 JSON 列中提取特定的键。

huangapple go评论84阅读模式
英文:

Unpack a specific key from json column

问题

我的数据如下所示:

col1   
[{"key":"1", "count":5, "desc":"blah"},{"key":"2", "count":3, "desc":"meh"}]
[{"key":"2", "count":23, "desc":"qwe"},{"key":"44", "count":0, "desc":""}]

我想创建一个新的列,其中只包含"key"的值:

new_col   
["1", "2"]
["2", "44"]

我尝试以各种方式解析JSON,但没有找到一个合理的方法来完成它。

英文:

My data look like:

col1   
[{"key":"1", "count":5, "desc":"blah"},{"key":"2", "count":3, "desc":"meh"}]
[{"key":"2", "count":23, "desc":"qwe"},{"key":"44", "count":0, "desc":""}]

I want to create new column which will include only the "key"'s values:

new_col   
["1", "2"]
["2", "44"]

I tried to parse the json in some ways but didn't find a reasonable way to get it done.

答案1

得分: 0

看起来你的一个单元格中有几个JSON对象。你可以在变体列上使用FLATTEN函数,将其展开为多行,然后提取其中的键,并将其聚合为一个数组。可以尝试以下代码:

SELECT ARRAY_AGG(FLATTENED.value:key) AS new_col
FROM my_variant_table, -- 替换为你的表名
     LATERAL FLATTEN(input => col1) AS FLATTENED
GROUP BY col1;

-- 我使用GROUP BY来确保行的唯一性

英文:

It looks like you have a couple of JSON object in one cell. You can use FLATTEN on your variant column to be able to select from it as it was in multiple rows. Then you extract the key from it and aggregate as an array. Try this:

SELECT ARRAY_AGG(FLATTENED.value:key) AS new_col
FROM my_variant_table, -- replace with your table name
     LATERAL FLATTEN(input => col1) AS FLATTENED
GROUP BY col1;

--group by I used to ensure the uniqueness of the rows

huangapple
  • 本文由 发表于 2023年8月9日 15:00:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865328.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定