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

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)

  • What if I want to add a value from the same json to an array in the same json. – Akhil yesterday
  • Can you give an example? – S-Man yesterday
  • 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. – Akhil yesterday
  • you want to get "new york" into the array? – S-Man yesterday
  • 1
    dbfiddle.uk/… – S-Man yesterday

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.