官方示例是这样的
select * from json_populate_record(null::myrowtype, '{"a": 1, "b": ["2", "a b"], "c": {"d": 4, "e": "a b c"}}');
select * from json_populate_recordset(null::myrowtype, '[{"a":1,"b":2},{"a":3,"b":4}]');
null::myrowtype是什么鬼???
网上好多教程是让你创建一张表,例如test,表结构和你的json结构一至,如下:
select * from json_populate_record(null::test, '[{"a":1,"b":2},{"a":3,"b":4}]');
select * from json_populate_recordset(null::test, '[{"a":1,"b":2},{"a":3,"b":4}]');
创建表麻烦且不便于管理.实际上可以用自定义类型代替
drop type if exists json_test_columns;
--根据json结构创建自定义类型
create type json_test_columns as (a int,b int,c int,d int);
--使用自定义类型输出
select * from json_populate_record(null::json_test_columns,'{"a":1,"b":2,"c":3,"d":4}');
select * from json_populate_recordset(null::json_test_columns,'[{"a":1,"b":2,"c":3,"d":4},{"a":2,"b":3,"c":4,"d":5}]');
--上面的压缩版本,目前还不支持,我个人觉得应该支持,
-- select * from json_populate_recordset(null::json_test_columns,'[[1,2,3,4],[2,3,4,5]]');
--变通方法
select value->>0 as a,value->>1 as b,value->>2 as c,value->>3 as c from (select * from jsonb_array_elements('[[1,2,3,4],[2,3,4,5]]')) as tmp;