Search code examples
postgresqljsonb

Add objects inside NESTED JSONB arrays with PostgreSQL


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?


Solution

  • 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