我如何 modify/update 数组中的多个值 json

How can I modify/update multiple values in a json array

假设我有一个数据库 jsonb 列,其中包含一个 json 数组,格式如下:

[
  {
    "test1key": "test1Value"
  },
  {
    "test2key": "test2Value"
  },
  {
    "test3key": "test3Value"
  }
]

是否可以在单个查询中更新"test1key"和"test2key"的值?如果是,怎么做?

主要问题是你为什么要这样做? JSON 结构不必要地复杂且不合逻辑。您应该使 JSON 数据尽可能简单。您可以将相同的数据存储在单个对象中:

{"test1key": "test1Value", "test2key": "test2Value", "test3key": "test3Value"}

然后更新就这么简单

update my_table
set json_col = json_col || '{"test1key": "newValue1", "test2key": "newValue2"}'
where id = 1

即使数据来自外部,您始终可以在将其保存到数据库之前将其转换为更简单、更高效的形式。过于复杂的数据结构使其处理(尤其是更新)困难且效率低下:

update my_table t1
set json_col = new_array
from (
    select id, jsonb_agg(jsonb_build_object(old_key, coalesce(new_value, old_value))) as new_array
    from my_table
    cross join jsonb_array_elements(json_col) as a(elem)
    cross join jsonb_each_text(elem) as e(old_key, old_value)
    left join jsonb_each_text(
        '{"test1key": "newValue1", "test2key": "newValue2"}'
        ) as v(new_key, new_value) 
    on old_key = new_key
    group by id
    ) t2
where t1.id = 1 and t2.id = t1.id;

在线演示:db<>fiddle.