Add element to JSON object in Postgres
use ||
to merge jsonb and set the value to it
example:
origin:
in table a
:
id | info
1 | {"aa":"bb"}
2 | {"aa":"cc"}
after executing:
update a set info = info::jsonb || ('{"id":' || id || '}' )::jsonb
generates:
id | info
1 | {"aa":"bb","id":1}
2 | {"aa":"cc","id":2}
something_else:
- use
-
‘key’
to delete element in jsonb - merge will replace origin one if the two jsonb has same key
If you upgrade to PG9.5.1, then you can use sql operator ||
to merge jsonb, example
select '{"a":1}'::jsonb || '{"a":2, "b":2}'::jsonb
will return {"a": 2, "b": 2}
If you can't upgrade to pg9.5.1, IMHO, doing the job in your code will be a better choice. You can parse old jsonb string as a map, and then update the map, then convert to string and update db-record.
And if we want to update (add) a JSONB field:
UPDATE <table>
SET <field-name> = <field-name> || '{"a": 1}'::jsonb
WHERE id = <some id>
Even I had the same problem, I wanted to dynamically append new elements to jsonb[].
Assume column_jsonb[] = [{"name":"xyz","age":"12"}]
UPDATE table_name
SET column_jsonb[] = array_append(column_jsonb[],'{"name":"abc","age":"22"}');
Result : [{"name":"xyz","age":"12"},{"name":"abc","age":"22"}]