如何更新嵌套 json Postgres 中的值

How to update value in nested json Postgres

我在“信息”列

中存储了以下JSON
{
  "customConfig": {
    "isCustomGoods": 1
  },
  "new_addfields": {
    "data": [
      {
        "val": {
          "items": [
            {
              "Code": "calorie",
              "Value": "365.76"
            },
            {
              "Code": "protein",
              "Value": "29.02"
            },
            {
              "Code": "fat",
              "Value": "23.55"
            },
            {
              "Code": "carbohydrate",
              "Value": "6.02"
            },
            {
              "Code": "spirit",
              "Value": "1.95"
            }
          ],
          "storageConditions": "",
          "outQuantity": "100"
        },
        "parameterType": "Nutrition",
        "name": "00000000-0000-0000-0000-000000000001",
        "label": "1"
      },
      {
        "name": "b4589168-5235-4ec5-bcc7-07d4431d14d6_Для ресторанов",
        "val": "true"
      }
    ]
  }
}

我想更新嵌套的值 json

{
  "name": "b4589168-5235-4ec5-bcc7-07d4431d14d6_Для ресторанов",
  "val": "true"
}

并将“val”设置为“Yes”str 所以结果应该像

{
  "name": "b4589168-5235-4ec5-bcc7-07d4431d14d6_Для ресторанов",
  "val": "Yes"
}

我该怎么做?假设我需要为数据库

中的许多记录更新 json 中的这个值

我们可以使用 Postgres 9.5+

提供的 jsonb_set()

来自Docs

jsonb_set(target jsonb, path text[], new_value jsonb [, create_missing boolean])

更新嵌套对象的查询:

UPDATE temp t
SET info = jsonb_set(t.info,'{new_addfields,data,1,val}', jsonb '"Yes"')
where id = 1;

也可以用在select查询中:

SELECT 
  jsonb_set(t.info,'{new_addfields,data,1,val}', jsonb '"Yes"')
FROM temp t
LIMIT 1;

考虑到您在 table 中有一个常量 JSON 结构和一个主键。 想法是获取元素 [=11] 的确切路径=] 具有值 true (可以在数组中的任何索引处),然后将其替换为所需的值。所以你可以像下面这样写你的查询:

with cte as (
select 
  id, 
  ('{new_addfields,data,'||index-1||',val}')::text[] as json_path
from 
  test, 
  jsonb_array_elements(info->'new_addfields'->'data') 
  with ordinality arr(vals,index) 
where 
  arr.vals->>'val' ilike 'true'
  )

 update test 
 set info = jsonb_set(info,cte.json_path,'"Yes"',false) 
 from cte 
 where test.id=cte.id;

DEMO