使用Postgres 11,如何转换此JSON对象(以文本索引和整数作为值)
{"a":{"col1":1,"col2":2,"col3":3}
,"b":{"col1":4,"col2":5,"col3":6}
,"c":{"col1":7,"col2":8,"col3":9}}
到类似这样的记录集:
r_id | col1 | col2 | col3
-------------------------
a | 1 | 2 | 3
b | 4 | 5 | 6
c | 7 | 8 | 9
答案 0 :(得分:0)
SELECT key AS r_id, value->>'col1' AS col1, value->>'col2' AS col2, value->>'col3' AS col3
FROM JSON_EACH('{"a":{"col1":1,"col2":2,"col3":3},"b":{"col1":4,"col2":5,"col3":6},"c":{"col1":7,"col2":8,"col3":9}}');
答案 1 :(得分:0)
Your solution对于三个值列似乎足够好。
列越多,json_populate_record()
会缩短语法并使其速度更快。但是,它基于模板行类型,而您没有。您可以通过创建一个临时表(在会话内部可见,直到会话结束)轻松提供它:
CREATE TEMP TABLE t1(col1 int, col2 int, col3 int);
SELECT key AS r_id, (json_populate_record(null::t1, value)).*
FROM json_each('{"a":{"col1":1,"col2":2,"col3":3}
, "b":{"col1":4,"col2":5,"col3":6}
, "c":{"col1":7,"col2":8,"col3":9}}')
如果您的JSON文档是一个记录数组,则可以使用json_populate_recordset()
:
CREATE TEMP TABLE t2(r_id text, col1 int, col2 int, col3 int);
SELECT *
FROM json_populate_recordset(null::t2
, '[{"r_id":"a","col1":1,"col2":2,"col3":3}
, {"r_id":"b","col1":4,"col2":5,"col3":6}
, {"r_id":"c","col1":7,"col2":8,"col3":9}]');