简体   繁体   中英

How to append a custom object to JSONB column type in postgres

I need to update a jsonb column which contains data {"X":true} . I need to append a complex object of the type {"obj":{"a":1,"b":2}} so the final value of row for that column {"x":true,"obj":{"a":1,"b":2}} . What will be the query to update this row.

postgres version 12

Update - The following query update tableName set columnName = (select '{"obj":{"a":1,"b":2}}'::jsonb || columnName::jsonb) where... returns successfully when there is a value present, but when the column is null it still remains null after running the update query. I need to be able to add {"obj":{"a":1,"b":2}} even when the column is null.

You can use the concatenation operator :

'{"X":true}'::jsonb || '{"obj":{"a":1,"b":2}}'::jsonb

If you want to update an existing column, use coalesce() to deal with NULL values:

update the_table
  set the_column = coalesce(the_column, '{}')||'{"obj":{"a":1,"b":2}}'

Online example

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