1

I have a json object column in a Postgres table. Suppose each record contains the value for this column similar to the below json

{"country":"USA","states":["Texas","Alaska"]}

How would I create an update statement to add a new state "Virginia" to the state array in that json column.

table name : person-details column name : location

1 Answer 1

1

demo:db<>fiddle

Using jsonb_insert():

UPDATE nations
SET nation = jsonb_insert(nation::jsonb, '{states,0}', '"Virginia"')::json
WHERE nation ->> 'country' = 'USA';

If your data type is json, then you'll need the casts into type jsonb and back (as shown)

Sign up to request clarification or add additional context in comments.

5 Comments

What if I want to add a value from the same json to an array in the same json.
Can you give an example?
sample json : {"country":"USA","states":["Texas","Alaska"], "other":"NewYork"} how would I update the value of states to contain the value present in other as well.
you want to get "new york" into the array?
I want to get the string whatever text is present in "other" to be addded to the states array. In this example , "New York"

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.