Sql 如何在Snowflake中将JSON键值作为数据列读取?
我有以下JSON示例:Sql 如何在Snowflake中将JSON键值作为数据列读取?,sql,json,snowflake-cloud-data-platform,Sql,Json,Snowflake Cloud Data Platform,我有以下JSON示例: { "Id1": { "name": "Item1.jpg", "Status": "Approved" }, "Id2": { "name": "Item2.jpg", "Status": "Approved"
{
"Id1": {
"name": "Item1.jpg",
"Status": "Approved"
},
"Id2": {
"name": "Item2.jpg",
"Status": "Approved"
}
}
我正在尝试获得以下输出:
_key name Status
Id1 Item1.jpg Approved
Id2 Item2.jpg Approved
在Snowflake中使用SQL有什么方法可以实现这一点吗?您应该在任何包含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)) ;
您应该在任何包含JSON数据的列中使用Snowflake的变量数据类型。让我们一步一步地将其分解:
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)) ;
谢谢,我确实发现展平功能正满足我的需要。但你们的回答让我的代码变得更好。谢谢,我确实发现展平函数满足了我的需要。但是你的回答让我的代码变得更好。