在具有文本字段的 postgresql 中更新 json 对象

update json object in postgresql having text field

我在 PostgreSQL 中有一列具有文本数据类型(数据文本)

这一栏的数据会像

[
 {"code":"ABC","Value":"A1"},
 {"code":"Name","Value":"Ramesh"},
 {"code":"Age","paramValue":"24"}
]

在上面json我想更新值如 {“代码”:“年龄”,“paramValue”:“30”}

数据会像

[
 {"code":"ABC","Value":"A1"},
 {"code":"Name","Value":"Ramesh"},
 {"code":"Age","paramValue":"30"}
]

因为它是 TEXT 字段,我尝试了不同的方法但无法成功

我试过先选择

SELECT id, data ::json->'"code":"ABC"' as name 
  FROM my_table;

我收到错误错误:json 类型的输入语法无效详细信息:应为“,”或“}”,但找到了

尝试以下查询:

with cte as (
             select id, '{'||b-1||', paramValue}' "path_" 
               from test, 
                    jsonb_array_elements(data::jsonb) with ordinality t(a,b)
              where a->>'code'='Age'
)
update test t1 
   set data=jsonb_set(t1.data::jsonb,path_::text[],'"30"'::jsonb) 
  from cte 
 where t1.id=cte.id

注意:只有当字段 data 中的值正确 JSON 并且每个数组 {"code":"Age","paramValue":"30"} 只有一个对象具有 'code' 作为 Age 时,以上解决方案才会生效=]

DEMO