Kev*_*sko 3 postgresql json jsonb postgresql-9.5
我将 JSON 数据存储在我的 postgresql 9.5 DB 的 JSONB 字段中。
有没有办法在不知道哪一列是子对象的情况下制作子对象列?
有问题的 JSON 示例:
{
"a":1,
"b":[1,2,3],
"c":"bar",
"d":{
"key1":"value1",
"key2":"value2"
}
}
Run Code Online (Sandbox Code Playgroud)
我可以使用以下内容从 JSON 对象中获取所有键。
SELECT * FROM json_object_keys('{"a":1,"b":[1,2,3],"c":"bar", "d":{"key1":"value1", "key2":"value2"}}')
那时我可以使用 json_to_record() 但我想将列拆分为它们自己的单独字段。
select * from json_to_record('{"a":1,"b":[1,2,3],"c":"bar", "d":{"key1":"value1", "key2":"value2"}}') as x(a int, b text, c text, d text)
得到我
a| b | c | d
1| [1,2,3] | bar | {"key1":"value1", "key2":"value2"}
Run Code Online (Sandbox Code Playgroud)
有没有办法让这样的东西回来,最好是在一个查询中?
--------------------------------------------------------------------
a| b | c | d | key1 | key2
1| [1,2,3] | bar | {"key1":"value1", "key2":"value2"} |value1 |value2
Run Code Online (Sandbox Code Playgroud)
WITH t(v) AS ( VALUES
('{
"a":1,
"b":[1,2,3],
"c":"bar",
"d":{
"key1":"value1",
"key2":"value2"
}
}'::JSONB)
)
SELECT x1.*,x2.* FROM t,
jsonb_to_record(v) as x1(a int,b text,c text,d jsonb),
jsonb_to_record(v->'d') as x2(key1 text,key2 text);
Run Code Online (Sandbox Code Playgroud)
结果:
a | b | c | d | key1 | key2
---+-----------+-----+--------------------------------------+--------+--------
1 | [1, 2, 3] | bar | {"key1": "value1", "key2": "value2"} | value1 | value2
(1 row)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1161 次 |
| 最近记录: |