简体   繁体   中英

Postgres how to turn a field into a json array

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}
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 ||

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM