我当前的 JSON 对象如下所示:
-- create a sample table
create or replace table json_example(v variant);
-- create sample json record
insert into json_example
select parse_json(
'[
{
"key": "variable_a",
"value": {
"double_value": null,
"float_value": null,
"int_value": null,
"string_value": "https://example.com"
}
},
{
"key": "variable_b",
"value": {
"double_value": null,
"float_value": null,
"int_value": 2,
"string_value": null
}
}
]');
这是我想要实现的简化 JSON:
{
"variable_a": "https://example.com",
"variable_b": 2
}
如何从多级 JSON 对象中获取简化的 JSON?
这就是我开始思考的方式:
select value:key::string as key, value:value:string_value::varchar as value
from json_example, lateral flatten(input => v)
union all
select value:key::string as key, value:value:int_value::varchar as value
from json_example, lateral flatten(input => v)
提前谢谢您。
最佳答案
因此,如果您希望所有内容都是 JSON 文本,您可以:
WITH data as (
select parse_json(
'[
{
"key": "variable_a",
"value": {
"double_value": null,
"float_value": null,
"int_value": null,
"string_value": "https://example.com"
}
},
{
"key": "variable_b",
"value": {
"double_value": null,
"float_value": null,
"int_value": 2,
"string_value": null
}
}
]') as json
)
SELECT f.value:key::text as t_key
,try_to_double(f.value:value:double_value::text) as d_val
,try_to_double(f.value:value:float_value::text) as f_val
,try_to_number(f.value:value:int_value::text) as n_val
,f.value:value:string_value::text as s_val
,coalesce(d_val::text, f_val::text, n_val::text, s_val) as c_val
,object_construct(t_key, c_val) as obj
FROM DATA, lateral flatten(input=>json) f
然后向我们展示如何构建 CASE 语句,并构建干净的 native 对象,例如:
SELECT
case
when not is_null_value(f.value:value:double_value)
then object_construct(f.value:key::text, try_to_double(f.value:value:double_value::text))
when not is_null_value(f.value:value:float_value)
then object_construct(f.value:key::text, try_to_double(f.value:value:float_value::text))
when not is_null_value(f.value:value:int_value)
then object_construct(f.value:key::text, try_to_number(f.value:value:int_value::text))
else
object_construct(f.value:key::text, f.value:value:string_value::text)
end obj
FROM DATA, lateral flatten(input=>json) f
可以将其变成单个对象,如下所示:
SELECT
object_agg(f.value:key,
case
when not is_null_value(f.value:value:double_value)
then try_to_double(f.value:value:double_value::text)
when not is_null_value(f.value:value:float_value)
then try_to_double(f.value:value:float_value::text)
when not is_null_value(f.value:value:int_value)
then try_to_number(f.value:value:int_value::text)
else
f.value:value:string_value
end
) as obj
FROM DATA, lateral flatten(input=>json) f
关于arrays - 如何取消嵌套 JSON 数据对象并使用 Snowflake 创建简化的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71834085/