jsonb_insert()

用于将值插入 jsonb 值的功能

jsonb_insert() 是一个系统函数,用于将一个 jsonb 值插入到现有的 jsonb 值中。

jsonb_insert() 添加于 PostgreSQL 9.6

用法

jsonb_insert ( target jsonb, path text[], new_value jsonb [, insert_after boolean ] ) → jsonb

如果 path 指定了一个数组元素,那么 new_value 将会

  • 被插入到该元素之前,如果 insert_afterfalse(默认值)
  • 被插入到该元素之后,如果 insert_aftertrue

如果 path 指定了一个对象字段,只有当该对象不包含该键时,new_value 才会被插入。

变更历史

示例

jsonb_insert() 的基本用法示例

postgres=# SELECT jsonb_insert('[1, 2, 4]', '{2}', '3');
 jsonb_insert 
--------------
 [1, 2, 3, 4]
(1 row)

如果 insert_aftertrue,则提供的值将插入到由 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.

分类

JSON, 系统函数

另请参阅

jsonb_set(), jsonb_set_lax()

反馈

就“jsonb_insert()”提交任何评论、建议或更正,请在此处 提交