简体   繁体   English

Postgres/JSON 更新嵌套数组元素

[英]Postgres/JSON Updating nested array elements

Given the input JSON from the 'table' under a column named '_value'.给定来自名为“_value”的列下的“表”的输入 JSON。 I would like to replace the field "sc" as text from object to value of name under sc.我想将字段“sc”作为文本从 object 替换为 sc 下的名称值。

The json before updating looks like this.更新前的json长这样。

{
    "iProps": [
    {
        "value": {
            "rules": [
                {
                    "ao": {
                        "sc": {
                            "web_link": "abc.com",
                            "name": "name"
                        }
                    }
                },
                {
                    "ao": {
                        "sc": ""
                    }
                }
            ]
        }
    }
]
}

The json after updating should look like this.更新后的json应该是这个样子。

{
    "iProps": [
    {
        "value": {
            "rules": [
                {
                    "ao": {
                        "sc":  "name"
                    }
                },
                {
                    "ao": {
                        "sc": ""
                    }
                }
            ]
        }
    }
]
}

I tried the below query to get to 'rules' array but having difficulty to proceed further in parsing and updating.我尝试了以下查询以获取“规则”数组,但在解析和更新方面难以进一步进行。

 WITH values AS (
    SELECT iprop -> 'value' -> 'rules' AS value FROM
    table t,jsonb_array_elements(t._value->'iProps') AS 
        iprop )
SELECT *
from values, jsonb_array_elements(values.ao)

throws following error引发以下错误

ERROR:  column values.ao does not exist
LINE 26: from values, jsonb_array_elements(values.ao)
                                           ^
SQL state: 42703
Character: 1396

You can try below mentioned query considering your structure is constant and the data type of your column is JSONB .考虑到您的结构是常量并且列的数据类型是JSONB ,您可以尝试下面提到的查询。

with cte as (
select 
 vals2->'ao'->'sc'->'name' as namevalue,
  ('{iProps,'||index1-1||',value,rules,'||index2-1||',ao,sc}')::text[] as json_path
from 
  table_, 
  jsonb_array_elements(value_->'iProps') 
  with ordinality arr1(vals1,index1),
  jsonb_array_elements(vals1->'value'->'rules') 
  with ordinality arr2(vals2,index2)

  )

 update table_ 
 set value_ = jsonb_set(value_,cte.json_path,cte.namevalue,false) 
 from cte
WHERE cte.namevalue IS NOT NULL

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM