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.

2 Answers 2

2

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

UPDATE test
SET data = jsonb_set(data, '{0,name}', '"Cortana"', true)
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 *;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy 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.