【问题标题】:Add objects inside NESTED JSONB arrays with PostgreSQL使用 PostgreSQL 在 NESTED JSONB 数组中添加对象
【发布时间】:2020-02-22 12:55:31
【问题描述】:

Json 请求

INSERT INTO test.demotbl (data)
VALUES ('{
    "x1": "Americas",
    "x2": "West",
    "x3": [{
        "x_id": "sam"
    }],
    "x4": {
        "a1": true,
        "a2": false,
        "a3": [
            "xx",
            "xx"
        ],
        "a4": [
            "Josh"
        ],
        "y1": [{
                "id": "RW",
                "z2": true,
                "z3": "USER"

            },
            {
                "id": "RO",
                "z2": false,
                "z3": "SELECT"

            }
        ]
    }
}'::jsonb)

我想根据 id 条件 "id": "RO".Eample 更新一个新的归档 z4 “z4”:[{ “姓名”:“约翰” }, { “名字”:“史蒂夫” }

预期输出:

{
    "x1": "Americas",
    "x2": "West",
    "x3": [{
        "x_id": "sam"
    }],
    "x4": {
        "a1": true,
        "a2": false,
        "a3": [
            "xx",
            "xx"
        ],
        "a4": [
            "Josh"
        ],
        "y1": [{
                "id": "RW",
                "z2": true,
                "z3": "USER"

            },
            {
                "id": "RO",
                "z2": false,
                "z3": "SELECT",
                "z4": [{
                    "name": "john"
                },{
                    "name": "Steve"
                }]
            }
        ]
    }
}

我可以使用什么 postgres JSONB sql 来实现上述输出?

【问题讨论】:

    标签: postgresql jsonb


    【解决方案1】:

    你应该可以这样做:

    with zd as (select ('{x4,y1,'||index-1||',z3}')::text[] as path
                from table1
                ,jsonb_array_elements((field1->>'x4')::jsonb->'y1') 
                with ordinality arr(x,index)
                where x->>'id'='RO'
            )
    update table1
    set field1=jsonb_set(field1,zd.path,'[{ "name": "john" }, { "name": "Steve" }]'::jsonb,true)
    from zd  
    

    请注意,jsonb_set 中的最后一个参数现在为 true,指示它在字段不存在时创建该字段。

    最好的问候,
    比亚尼

    【讨论】:

    • Thnaks @Bjarni 完美解决方案 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2019-07-20
    相关资源
    最近更新 更多