简体   繁体   中英

Updating value inside json data PSQL

I have a table that contains tables stores in data column as a JSON using psql, trying to update specific cell in the (data column) which is array of objects.

for example, updating the "first_name":"Fergus" to "first_name":"Marcus" where "id":"1"

CREATE TABLE tables(
    table_id SERIAL PRIMARY KEY,
    table_name VARCHAR(100) NOT NULL,
    user_id VARCHAR(100) NOT NULL,
    data json
);

INSERT INTO tables (table_name, user_id, data)
VALUES (
'Supplier Info', 4, '[
{"id":"1","first_name":"Fergus","last_name":"Flipsen","email":"fflipsen0@ezinearticles.com","gender":"Male"},
 {"id":"2","first_name":"Vincenz","last_name":"Russan","email":"vrussan1@independent.co.uk","gender":"Male"}
]'::JSON);

It is not that easy (and, as commented by a_horse_with_no_name, it would be much simpler with a normalized schema).

Basically, you need to unnest the inner array, modify the relevant object, then aggregate back into an array.

You can do this with a correlated subquery, jsonb_array_elements() and conditional logic in jsonb_agg() :

update tables t
set data = (
    select 
        jsonb_agg(
            case when (x.obj ->> 'id')::int = 1 
                then x.obj || '{"first_name": "Marcus"}'
                else x.obj
            end
            order by x.ord
        ) new_data
    from jsonb_array_elements(t.data) with ordinality x(obj, ord)
)

Demo on DB Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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