Renaming properties in JSONB
To rename a property in a JSON column from foo to bar. in PostgreSQL you can use the jsonb_set function in combination with the #- operator (which removes the specified key from a JSONB object) to achieve this. Here’s a general approach to rename a property:
- Remove the old key (
foo): Use the#-operator to remove thefookey from the JSONB column. - Add the new key (
bar): Usejsonb_setto add thebarkey with the value previously underfoo.
Here’s how you could write the SQL statement:
UPDATE recipes SET contents = jsonb_set(contents #- '{foo}', '{bar}', contents->'foo') WHERE contents ? 'foo';
This query does the following:
contents #- '{foo}'removes thefookey (and its value) from thecontents.jsonb_setis then used to add a new keybarwith the value thatfoohad. The{bar}argument specifies the path where the new key is added, andcontents->'foo'specifies the value to be set for the new key.- The
WHEREclause ensures that this operation only affects rows wherecontentshas thefookey.