表faults
包含列recacc
(jsonb),其中包含json对象数组。它们每个都包含一个字段action
。如果action
的值为abc
,我想将其更改为cba
。更改将应用于所有行。
[
{
"action": "abc",
"created": 1128154425441
},
{
"action": "lmn",
"created": 1228154425441
},
{
"action": "xyz",
"created": 1328154425441
}
]
以下操作无效,可能是因为数据为数组格式
update faults
set recacc = jsonb_set(recacc,'{action}', to_jsonb('cbe'::TEXT),false)
where recacc ->> 'action' = 'abc'
答案 0 :(得分:0)
我不确定这是否是最好的选择,但是您可能首先使用jsonb_array_elements
获取jsonb的元素,将其替换,然后使用array_agg
和array_to_json
来重建json
UPDATE faults SET recacc = new_recacc::jsonb
FROM
(SELECT array_to_json(array_agg(s)) as new_recacc
FROM
( SELECT
replace(c->>'action','abc','cba') , --this to change the value
c->>'created' FROM faults f
cross join lateral jsonb_array_elements(f.recacc) as c
) as s (action,created)
) m;