jsonb_set() 是一个系统函数,用于在 jsonb 值中,通过指定的路径替换或创建某个项。
jsonb_set() 在 PostgreSQL 9.5 中添加。
用法
jsonb_set (targetjsonb,
pathtext[],
new_valuejsonb
[,create_if_missingboolean]
)→jsonb
如果提供的 path 对于 target 无效,则该路径会被忽略,并返回未更改的 target。
如果提供的 path 包含的目标 jsonb 值中不存在的键,该键将被插入,除非 create_if_missing 被显式设置为 false。
变更历史
示例
jsonb_set() 的基本用法示例
postgres=# SELECT jsonb_set('["foo","bar"]', '{1}', '"baz"');
jsonb_set
----------------
["foo", "baz"]
(1 row)
在此示例中,jsonb 数组的第二个元素已被新值替换。
包含在 path 中的负整数从各自数组的末尾开始计数。
postgres=# SELECT jsonb_set('[1,2,3]','{-1}', '99');
jsonb_set
------------
[1, 2, 99]
(1 row)
如果 path 指向一个不存在的项,它将被插入,除非 create_if_missing 被设置为 false。
postgres=# SELECT jsonb_set('["foo","bar"]', '{2}', '"baz"');
jsonb_set
-----------------------
["foo", "bar", "baz"]
(1 row)
postgres=# SELECT jsonb_set('["foo","bar"]', '{2}', '"baz"', false);
jsonb_set
----------------
["foo", "bar"]
(1 row)
在 path 中指定的负整数,如果指向数组的起始位置之前,将导致该值被添加到数组的开头。
postgres=# SELECT jsonb_set('["foo","bar"]', '{-3}', '"baz"');
jsonb_set
-----------------------
["baz", "foo", "bar"]
(1 row)
在 json 对象中指定带有键的 path。
postgres=# SELECT jsonb_set('{"foo": 1, "bar": 2}', '{"bar"}', '99');
jsonb_set
-----------------------
{"bar": 99, "foo": 1}
(1 row)
修改多维数组。
postgres=# SELECT jsonb_set('[ [1,2], [3,4] ]', '{0,1}', '99');
jsonb_set
-------------------
[[1, 99], [3, 4]]
(1 row)
参考资料
- PostgreSQL 文档: JSON 处理函数
有用链接
- PostgreSQL jsonb_set() 函数 - Neon, Inc. 教程
