Home > OS >  Add property to the top level of a jsonb object
Add property to the top level of a jsonb object

Time:11-14

From the documentation I can figure out how to replace or add a value at from an existing property

{"example":123}
UPDATE mytable
SET jsoncolumn = jsonb_set(jsoncolumn, '{example}', '"string123"')
WHERE id = 1;
{"example":"string123"}

However, I cannot figure out how to insert a property at the top level (beside a sibling)

{"example":123}
{"example":123,"property-to-add":"value"}

What is the easiest way to accomplish this (given that the actual object is pretty large)

CodePudding user response:

You can append the new key/value pair:

UPDATE mytable
  SET jsoncolumn = jsoncolumn || '{"property-to-add": "value"}'
WHERE id = 1;

If property-to-add already exists, it will be replaced.

  • Related