Lok*_*sal 2 sql json snowflake-cloud-data-platform
我有以下示例 JSON:
{
"Id1": {
"name": "Item1.jpg",
"Status": "Approved"
},
"Id2": {
"name": "Item2.jpg",
"Status": "Approved"
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试获得以下输出:
_key name Status
Id1 Item1.jpg Approved
Id2 Item2.jpg Approved
Run Code Online (Sandbox Code Playgroud)
有什么方法可以使用 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)) ;
Run Code Online (Sandbox Code Playgroud)