PostgreSQL: Remove attribute from JSON column

前端 未结 8 1904
深忆病人
深忆病人 2020-12-13 12:13

I need to remove some attributes from a json type column.

The Table:

CREATE TABLE my_table( id VARCHAR(80), data json);
INSERT INTO my_table (id, dat         


        
8条回答
  •  遥遥无期
    2020-12-13 12:47

    This has gotten much easier with PostgreSQL 9.5 using the JSONB type. See JSONB operators documented here.

    You can remove a top-level attribute with the "-" operator.

    SELECT '{"a": {"key":"value"}, "b": 2, "c": true}'::jsonb - 'a'
    // -> {"b": 2, "c": true}
    

    You can use this within an update call to update an existing JSONB field.

    UPDATE my_table SET data = data - 'attrB'
    

    You can also provide the attribute name dynamically via parameter if used in a function.

    CREATE OR REPLACE FUNCTION delete_mytable_data_key(
        _id integer,
        _key character varying)
      RETURNS void AS
    $BODY$
    BEGIN
        UPDATE my_table SET
            data = data - _key
        WHERE id = _id;
    END;
    $BODY$
      LANGUAGE plpgsql VOLATILE
      COST 100;
    

    The reverse operator is the "||", in order to concatenate two JSONB packets together. Note that the right-most use of the attribute will overwrite any previous ones.

    SELECT '{"a": true, "c": true}'::jsonb || '{"a": false, "b": 2}'::jsonb 
    // -> {"a": false, "b": 2, "c": true}
    

提交回复
热议问题