简体   繁体   English

如何将 JSON 字典列表转换为 Snowflake 中的字符串列表?

[英]How can I convert a JSON list of dicts to a list of strings in Snowflake?

I have a Snowflake table which contains an id column and a favorite_books column.我有一个雪花表,其中包含一个id列和一个favorite_books列。 The favorite_books column contains a list of dictionaries in JSON. favorite_books列包含 JSON 中的字典列表。 Each dictionary has a title and a ISBN attribute:每个字典都有一个title和一个ISBN属性:

ID | favorite_books
--------------------
42 | [{"title": "LotR", "ISBN": "9780261102354"}, {"title": "HP1", "ISBN": "9780545582889"}]
13 | [{"title": "Faust", "ISBN": "9780192835956"}]

My real case is more complicated, but the part that is missing is to select only the titles.我的真实情况更复杂,但缺少的部分是 select 仅标题。 So the result should be:所以结果应该是:

ID | favorite_books
--------------------
42 | ["LotR", "HP1"]
13 | ["Faust"]

I saw Querying Semi-Structured Data , but I'm still not sure how to do that.我看到了Querying Semi-Structured Data ,但我仍然不知道该怎么做。

Adapting an existing answer for a similar data structure , you can try it this way (using a CTE, exploding the array, then grouping it back into a new array based on the ID): 为类似的数据结构调整现有答案,您可以尝试这种方式(使用 CTE,分解数组,然后根据 ID 将其分组回新数组):

with elements as (
    select ID, elements.value:title as title
    from table_name, LATERAL FLATTEN(input => favorite_books) elements
)
select elements.ID, ARRAY_AGG(elements.title) as favorite_books from elements
group by ID;

Or via a javascript UDF that's more straight-forward (just transforms the array):或者通过更直接的 javascript UDF(只是转换数组):

create or replace function extract_titles(A array)
  returns array
  language javascript
  strict
  as
  $$
    return A.map(function(d) {return d.title});
  $$
;

select ID, EXTRACT_TITLES(favorite_books) as favorite_books from table_name;

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

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