如何在 postgres 中定义 JSON 记录类型

Byo*_*uel 4 postgresql

查看 JSON 函数的 postgres 文档(https://www.postgresql.org/docs/9.6/static/functions-json.html),有一个部分我不明白如何将 JSON 对象扩展为一组行。

文档给出了此函数的示例用法json_populate_recordset(base anyelement, from_json json)select * from json_populate_recordset(null::myrowtype, '[{"a":1,"b":2},{"a":3,"b":4}]')

但我不确定第一个参数(null::myrowtype)是什么——表定义?

该函数的描述是:将from_json中最外层的对象数组扩展为一组行,其列与base定义的记录类型匹配(见下面的注释)。

底部的注释似乎都不相关。我希望通过示例代码得到更好的解释来理解这一切。

JGH*_*JGH 5

第二个通知是文档中感兴趣的通知之一,因为它解释了如何处理缺失的字段/值

注意:在 json_populate_record、json_populate_recordset、json_to_record 和 json_to_recordset 中,来自 JSON 的类型强制是“尽力而为”,并且可能不会为某些类型带来所需的值。JSON 键与目标行类型中的相同列名称匹配。未出现在目标行类型中的 JSON 字段将从输出中省略,不匹配任何 JSON 字段的目标列将简单地为 NULL。

json_populate_recordset将 json 对象的名称映射到作为第一个参数给出的表中的列名称。

create table public.test (a int, b text);

select * from json_populate_recordset(null::public.test, '[{"a":1,"b":"b2"},{"a":3,"b":"b4"}]');


 a | b
---+----
 1 | b2
 3 | b4
(2 rows)

--Wrong column name:
select * from json_populate_recordset(null::public.test, '[{"a":1,"c":"c2"},{"a":3,"c":"c4"}]');
 a | b
---+---
 1 |
 3 |
(2 rows)


--Wrong datatype:
select * from json_populate_recordset(null::public.test, '[{"a":1.1,"b":22},{"a":3.1,"b":44}]');

ERROR:  invalid input syntax for integer: "1.1"
Run Code Online (Sandbox Code Playgroud)

或者,您可以动态定义列,而不是使用现有表中的列名称/类型

select * from json_to_recordset('[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]') as x(a int, b text);
 a |  b
---+-----
 1 | foo
 2 |
(2 rows)
Run Code Online (Sandbox Code Playgroud)

--> 请注意,发生默认类型转换(“2”映射到 2),忽略缺失字段(b,在第二条记录中)以及未定义的字段(c)