Add objects inside NESTED JSONB arrays with PostgreSQL

帅比萌擦擦* 提交于 2020-03-25 12:34:19

问题


Json Request

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)

I want to update a new filed z4 based on id condition "id": "RO".Eample "z4": [{ "name": "john" }, { "name": "Steve" }

expected output :

{
    "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"
                }]
            }
        ]
    }
}

what postgres JSONB sql i can use to achive the above output?


回答1:


You should be able to do this with this:

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  

Note the last argument in jsonb_set is now true, which instructs it to create the field if it doesn't exist.

Best regards,
Bjarni



来源:https://stackoverflow.com/questions/60352354/add-objects-inside-nested-jsonb-arrays-with-postgresql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!