0

I saved a json like this in a column of my db:

{"a":137,"b":"28","c":"1","d":"5","e":19,"f":true}

is it possible with a query to transform "e" into an array without removing the value?

{"a":137,"b":"28","c":"1","d":"5","e":[19],"f":true}

1 Answer 1

1
update the_table
  set the_column = the_column||jsonb_build_object('e', array_to_json(array[the_column -> 'e']))
where ...

array[the_column -> 'e'] creates a "native" array out of the single element referenced by the key 'e'. This array is converted to JSON and a new JSON value is created using jsonb_build_object() which is then concatenated to the existing value. This will overwrite the existing key "e".

The above assumes that the column is defined as jsonb (which it should be). If it's only json you need to cast it to make the replacement work with ||

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

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.