0
create table test add column data jsonb;insert into test values (     '[{        "name": "Alexa",         "age": "20"    },     {        "name": "Siri",         "age": "42"    }]' );

Table Data Looks like this:

data <------ column_name

[{"name": "Alexa", "age": "20"}, {"name": "Siri", "age": "42"}]

I am familiar with how to update json data, Here i want to take json data from array and change it.I want to change "name" attribute of first json object "Alexa" to "Cortana", Is it possible to do that is postgres?P.S. This is not the actual data that I have broken down my doubt to simple problem.

askedMar 12, 2022 at 8:13
Ayush Naithani's user avatar

2 Answers2

2

You can use thejsonb_set function to return a JSON object with a section replaced with a new value

UPDATE testSET data = jsonb_set(data, '{0,name}', '"Cortana"', true)
answeredMar 12, 2022 at 8:28
Iain Shelvington's user avatar
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, can i set that to null? I did the same but it doesn’t seem to be working for null?
@AyushNaithani you should be able to pass the string'null' as the third parameter, what did you try?
It worked now i was writing NULL. Thanks
0

Hopefully the following command also works.

    update test set data = data - 0 || jsonb_build_object('name','Cortana', 'age', '20') returning *;
answeredMar 12, 2022 at 11:15
jian's user avatar

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.