json_populate_recordset() 是一个系统函数,它将顶级 JSON 对象数组展开为一组行。
json_populate_recordset() 在 PostgreSQL 9.3 中添加。
用法
json_populate_recordset (baseanyelement,from_jsonjson) → setofanyelement
base 参数必须是一个复合类型,其列名与 JSON 字段相对应。
变更历史
- PostgreSQL 9.3
- 添加 (提交 a570c98d)
示例
json_populate_recordset() 的基本用法示例
postgres=# CREATE TYPE foobar AS (id INT, val TEXT); CREATE TYPE postgres=# SELECT * FROM json_populate_recordset(NULL::foobar, '[{"id":1,"val":"foo"}, {"id":2,"val":"bar"}]'); id | val ----+----- 1 | foo 2 | bar (2 rows)
如果提供的 JSON 对象不包含与预期列名匹配的字段,则将发出 NULL 值。
postgres=# SELECT id IS NULL, id, val IS NULL, val
FROM json_populate_recordset(NULL::foobar, '[{"a":1,"val":"foo"}, {"id":2,"b":"bar"}]');
?column? | id | ?column? | val
----------+----+----------+-----
t | | f | foo
f | 2 | t |
(2 rows)
如果 JSON 对象包含无法转换为预期列数据类型的值,则会引发错误。
postgres=# SELECT * FROM json_populate_recordset(NULL::foobar, '[{"id":"baz","val":"foo"}, {"id":2,"val":"bar"}]');
ERROR: invalid input syntax for type integer: "baz"
参考资料
- PostgreSQL 文档: JSON 处理函数
另请参阅
jsonb_populate_recordset(), json_populate_record(), json_to_recordset()
