PostgreSQL rename attribute in jsonb field

后端 未结 3 957
野性不改
野性不改 2020-11-30 03:39

In postgresql 9.5, is there a way to rename an attribute in a jsonb field?

For example:

{ \"nme\" : \"test\" }

should be renamed t

3条回答
  •  借酒劲吻你
    2020-11-30 04:14

    I used the following for handling nested attributes and skipping any json that doesn't use the old name:

    UPDATE table_name
    SET json_field_name = jsonb_set(json_field_name #- '{path,to,old_name}',
                                    '{path,to,new_name}',
                                    json_field_name#>'{path,to,old_name}')
    WHERE json_field_name#>'{path,to}' ? 'old_name';
    

    just for reference docs:

    • #- Delete the field or element with specified path (for JSON arrays, negative integers count from the end) https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSONB-OP-TABLE

    • #>Get JSON object at the specified path https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-OP-TABLE

提交回复
热议问题