gpt4 book ai didi

sql - 如何读取 JSON 键值作为 Snowflake 中的数据列?

转载 作者:行者123 更新时间:2023-12-02 16:42:07 25 4
gpt4 key购买 nike

我有以下示例 JSON:

{
"Id1": {
"name": "Item1.jpg",
"Status": "Approved"
},
"Id2": {
"name": "Item2.jpg",
"Status": "Approved"
}
}

我正在尝试获得以下输出:

_key    name        Status
Id1 Item1.jpg Approved
Id2 Item2.jpg Approved

有什么方法可以使用 SQL 在 Snowflake 中实现这一点?

最佳答案

您应该在任何包含 JSON 数据的列中使用 Snowflake 的 VARIANT 数据类型。让我们逐步分解:

create temporary table FOO(v variant); -- Temp table to hold the JSON. Often you'll see a variant column simply called "V"

-- Insert into the variant column. Parse the JSON because variants don't hold string types. They hold semi-structured types.
insert into FOO select parse_json('{"Id1": {"name": "Item1.jpg", "Status": "Approved"}, "Id2": {"name": "Item2.jpg", "Status": "Approved"}}');

-- See how it looks in its raw state
select * from FOO;

-- Flatten the top-level JSON. The flatten function breaks down the JSON into several usable columns
select * from foo, lateral flatten(input => (foo.v)) ;

-- Now traverse the JSON using the column name and : to get to the property you want. Cast to string using ::string.
-- If you must have exact case on your column names, you need to double quote them.
select KEY as "_key",
VALUE:name::string as "name",
VALUE:Status::string as "Status"
from FOO, lateral flatten(input => (FOO.V)) ;

关于sql - 如何读取 JSON 键值作为 Snowflake 中的数据列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61429040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com