【问题标题】:Postgres/JSON Updating nested array elementsPostgres/JSON 更新嵌套数组元素
【发布时间】:2021-04-17 05:13:42
【问题描述】:

给定来自名为“_value”的列下的“表”的输入 JSON。我想将字段“sc”替换为从对象到 sc 下名称值的文本。

更新前的json是这样的

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

更新后的json应该是这样的

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

我尝试了以下查询以获取“规则”数组,但难以进一步进行解析和更新。

 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)

引发以下错误

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

【问题讨论】:

    标签: sql postgresql sql-update jsonb postgresql-9.5


    【解决方案1】:

    考虑到您的结构是不变的并且您的列的数据类型是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

    【讨论】:

    • 此查询有效,但有时在 cte.namevalue 为 null 时会遇到 null 约束。您认为添加“WHERE cte.namevalue IS NOT NULL”会解决问题吗?我是否错过了发现任何其他错误?
    • 这里索引 1 是 1,因为 iProps 在数组中有一个对象,而 index2 是 1 和 2,因为内部数组中有 2 个对象。但我不明白为什么这个查询不更新第二条规则。 json 路径 iProps -> 值 -> 规则 -> ao -> sc -> name = "name2"。 dbfiddle.uk/…
    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 2017-04-26
    • 1970-01-01
    • 2017-01-05
    • 2020-03-16
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多