如何使用 Postgres 在根级别更新多个 json 字段?

How to update multiple json fields at root level with Postgres?

我正在尝试更新一个 json 供稿的 agecity 字段,使用:

select jsonb_set(d,'{0,age,city}',d || '{"age":30,"city":"los angeles"}') 
from (
  values ('{"name":"john", "age":26,"city":"new york city"}'::jsonb)
) t(d);

但我得到的是:

{"age": 26, "city": "new york city", "name": "john"}

而不是预期的:

{"age": 30, "city": "los angeles", "name": "john"}

这意味着 none 个需要的字段已更新。

我已经看过了:

并查看了相关文档,但我无法正确理解。有帮助吗?

来自the documentation:

All the items of the path parameter of jsonb_set as well as jsonb_insert except the last item must be present in the target.

查询中给出的路径不满足上述条件。实际上,jsonb_set() 对根级别的对象不起作用,唯一的方法是使用 || 运算符:

select d || '{"age":30,"city":"los angeles"}'
from (
    values ('{"name":"john", "age":26,"city":"new york city"}'::jsonb)
) t(d);

                      ?column?                      
----------------------------------------------------
 {"age": 30, "city": "los angeles", "name": "john"}
(1 row) 

也许您可以使用空路径是合乎逻辑的

select jsonb_set(d, '{}', d || '{"age":30,"city":"los angeles"}')

遗憾的是,jsonb开发者并没有提供这样的可能性。