jsonb_insert() 是一个系统函数,用于将一个 jsonb 值插入到现有的 jsonb 值中。
jsonb_insert() 添加于 PostgreSQL 9.6。
用法
jsonb_insert (targetjsonb,pathtext[],new_valuejsonb[,insert_afterboolean] ) →jsonb
如果 path 指定了一个数组元素,那么 new_value 将会
- 被插入到该元素之前,如果
insert_after是false(默认值) - 被插入到该元素之后,如果
insert_after是true
如果 path 指定了一个对象字段,只有当该对象不包含该键时,new_value 才会被插入。
变更历史
- PostgreSQL 9.6
- 添加(提交 0b62fd03)
示例
jsonb_insert() 的基本用法示例
postgres=# SELECT jsonb_insert('[1, 2, 4]', '{2}', '3');
jsonb_insert
--------------
[1, 2, 3, 4]
(1 row)
如果 insert_after 是 true,则提供的值将插入到由 path 指定的项的之后。
postgres=# SELECT jsonb_insert('[1, 2, 4]', '{2}', '3', true);
jsonb_insert
--------------
[1, 2, 4, 3]
(1 row)
包含在 path 中的负整数从相应数组的末尾开始计数。
epp=# SELECT jsonb_insert('[1, 2, 4]', '{-3}', '3');
jsonb_insert
--------------
[3, 1, 2, 4]
(1 row)
如果负值延伸到数组的开头之外,则该值将被添加到数组的开头。
epp=# SELECT jsonb_insert('[1, 2, 4]', '{-99}', '3', true);
jsonb_insert
--------------
[3, 1, 2, 4]
(1 row)
将值插入由键引用的对象
postgres=# SELECT jsonb_insert('[{"foo": [0,1], "bar": [3,4]}]', '{0, bar, 1}', '99');
jsonb_insert
--------------------------------------
[{"bar": [3, 99, 4], "foo": [0, 1]}]
(1 row)
插入由键指定的 new object
epp=# SELECT jsonb_insert('{"foo": "bar"}', '{"baz"}', '"zoo"');
jsonb_insert
------------------------------
{"baz": "zoo", "foo": "bar"}
(1 row)
如果键已存在,将引发 ERROR。
epp=# SELECT jsonb_insert('{"foo": "bar"}', '{"foo"}', '"zoo"');
ERROR: cannot replace existing key
HINT: Try using the function jsonb_set to replace key value.
参考资料
- PostgreSQL 文档: JSON 处理函数
