PostgreSQL: Remove attribute from JSON column

前端 未结 8 1906
深忆病人
深忆病人 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:50

    While this is certainly easier in 9.5+ using the jsonb operators, the function that pozs wrote to remove multiple keys is still useful. For example, if the keys to be removed are stored in a table, you could use the function to remove them all. Here is an updated function, using jsonb and postgresql 9.5+:

    CREATE FUNCTION remove_multiple_keys(IN object jsonb, 
                                         variadic keys_to_delete text[], 
                                         OUT jsonb)
      IMMUTABLE
      STRICT
      LANGUAGE SQL
    AS 
    $$
      SELECT jsonb_object_agg(key, value)
         FROM (SELECT key, value 
               FROM jsonb_each("object")
               WHERE NOT (key = ANY("keys_to_delete")) 
         ) each_subselect
    $$
    ;
    

    If the keys to be removed are stored in a table, (e.g. in the column "keys" of the table "table_with_keys") you could call this function like this:

    SELECT remove_multiple_keys(my_json_object, 
                                VARIADIC (SELECT array_agg(keys) FROM table_with_keys));
    
    0 讨论(0)
  • 2020-12-13 12:51

    Simply use the #- operator, for example:

    SELECT '{"foo": 10, "bar": [], "baz": {}}'::jsonb #- '{baz}';
    
    0 讨论(0)
提交回复
热议问题