使用flatten使用Snowflake SQL解析JSON

5vf7fwbs  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(136)

我有以下代码,它从列中包含JSON数据的表创建了一个临时表。

CREATE TEMP TABLE temp_table AS
(
    WITH 
    var1 AS (
        SELECT ts
            ,col1 AS details
        FROM raw_temp_table
            ,TABLE (flatten(input => $1,OUTER => TRUE)) var1
        )
    ,var2 AS (
        SELECT var1.ts
            ,col1 AS details
            ,details: "json_attr1" AS attr1
            ,details: "json_attr2" AS attr2
        FROM var1
            ,TABLE (flatten(input => $2,OUTER => TRUE)) var2
        WHERE KEY = 'some_key'  -- "some-key" is not a column in any of the tables, but it is an attribute in the JSON
        )
    SELECT * FROM var2
);

字符串
解析的json看起来像这样:

{
    "json_attr1": "val1",
    "json_attr2": {
        "data": [{...}]
    }
}


我想从data数组中获取对象,然后创建一个新表来保存它们,或者以某种方式将它们作为列添加到临时表中,因为我将在新查询中解析它们。我尝试添加一个新的var,但我不知道如何使用结果。我还对,TABLE(flatten(input => $2)) var2 WHERE KEY = "some_key"部分的具体功能感兴趣,因为我找不到任何其他例子。
有没有一种方法可以使用该查询将data数组添加到表中?

mrwjdhj3

mrwjdhj31#

请检查以下查询是否为您服务。这里我用的是横向展平,这更方便。
Flatten将简单地展开任何嵌套对象并将它们放置到单独的行中。

WITH fake_table as (
    select parse_json('{
            "json_attr1": "val1",
            "json_attr2": {
                "data": [{"nest1":"nestval1","nest2":"nestval2"}
                        ,{"nest1":"nestval3","nest2":"nestval4"}]
            }
        }') raw
    
) 
,var1 AS (
    SELECT l1.key l1_key,l2.key l2_key,l4.key l4_key,l4.value::varchar l4_value
    -- select l3.*
    FROM fake_table
        ,lateral flatten(input => raw) l1
        ,lateral flatten(input => l1.value) l2
        ,lateral flatten(input => l2.value) l3
        ,lateral flatten(input => l3.value) l4
    where l4_key = 'nest1'
    )
SELECT * FROM var1;

字符串

相关问题