简体   繁体   English

PostgreSQL:从 JSON 列中删除属性

[英]PostgreSQL: Remove attribute from JSON column

I need to remove some attributes from a json type column.我需要从 json 类型列中删除一些属性。

The Table:桌子:

CREATE TABLE my_table( id VARCHAR(80), data json);
INSERT INTO my_table (id, data) VALUES (
  'A', 
  '{"attrA":1,"attrB":true,"attrC":["a", "b", "c"]}'
);

Now, I need to remove attrB from column data .现在,我需要从列data中删除attrB

Something like alter table my_table drop column data->'attrB';类似于alter table my_table drop column data->'attrB'; would be nice.会好的。 But a way with a temporary table would be enough, too.但是使用临时表的方法也足够了。

Update : for 9.5+, there are explicit operators you can use with jsonb (if you have a json typed column, you can use casts to apply a modification):更新:对于 9.5+,您可以将显式运算符与jsonb使用(如果您有一个json类型的列,则可以使用强制转换来应用修改):

Deleting a key (or an index) from a JSON object (or, from an array) can be done with the - operator:可以使用-运算符从 JSON 对象(或从数组)中删除键(或索引):

SELECT jsonb '{"a":1,"b":2}' - 'a', -- will yield jsonb '{"b":2}'
       jsonb '["a",1,"b",2]' - 1    -- will yield jsonb '["a","b",2]'

Deleting, from deep in a JSON hierarchy can be done with the #- operator:可以使用#-运算符从 JSON 层次结构的深处删除:

SELECT '{"a":[null,{"b":[3.14]}]}' #- '{a,1,b,0}'
-- will yield jsonb '{"a":[null,{"b":[]}]}'

For 9.4, you can use a modified version of the original answer (below), but instead of aggregating a JSON string, you can aggregate into a json object directly with json_object_agg() .对于 9.4,您可以使用原始答案的修改版本(如下),但不是聚合 JSON 字符串,而是可以直接使用json_object_agg()聚合为json对象。

Related: other JSON manipulations whithin PostgreSQL:相关:PostgreSQL 中的其他 JSON 操作:

Original answer (applies to PostgreSQL 9.3):原始答案(适用于 PostgreSQL 9.3):

If you have at least PostgreSQL 9.3, you can split your object into pairs with json_each() and filter your unwanted fields, then build up the json again manually.如果您至少有 PostgreSQL 9.3,您可以使用json_each()将您的对象拆分成对并过滤您不需要的字段,然后再次手动构建 json。 Something like:就像是:

SELECT data::text::json AS before,
       ('{' || array_to_string(array_agg(to_json(l.key) || ':' || l.value), ',') || '}')::json AS after
FROM (VALUES ('{"attrA":1,"attrB":true,"attrC":["a","b","c"]}'::json)) AS v(data),
LATERAL (SELECT * FROM json_each(data) WHERE "key" <> 'attrB') AS l
GROUP BY data::text

With 9.2 (or lower) it is not possible.使用 9.2(或更低版本)是不可能的。

Edit :编辑

A more convenient form is to create a function, which can remove any number of attributes in a json field:一种更方便的形式是创建一个函数,它可以删除json字段中任意数量的属性:

Edit 2 : string_agg() is less expensive than array_to_string(array_agg())编辑 2string_agg()array_to_string(array_agg())便宜

CREATE OR REPLACE FUNCTION "json_object_delete_keys"("json" json, VARIADIC "keys_to_delete" TEXT[])
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT COALESCE(
  (SELECT ('{' || string_agg(to_json("key") || ':' || "value", ',') || '}')
   FROM json_each("json")
   WHERE "key" <> ALL ("keys_to_delete")),
  '{}'
)::json
$function$;

With this function, all you need to do is to run the query below:使用此功能,您需要做的就是运行以下查询:

UPDATE my_table
SET data = json_object_delete_keys(data, 'attrB');

This has gotten much easier with PostgreSQL 9.5 using the JSONB type.使用 JSONB 类型的 PostgreSQL 9.5 使这变得更加容易。 See JSONB operators documented here .见JSONB运营商记录在这里

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.您可以在更新调用中使用它来更新现有的 JSONB 字段。

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.反向运算符是“||”,以便将两个 JSONB 数据包连接在一起。 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}

I couldn't get SELECT '{"a": "b"}'::jsonb - 'a';我找不到SELECT '{"a": "b"}'::jsonb - 'a'; to work in 9.5.2.在 9.5.2 中工作。 However, SELECT '{"a": "b"}'::jsonb #- '{a}';但是, SELECT '{"a": "b"}'::jsonb #- '{a}'; did work!没有工作!

只需使用#-运算符,例如:

SELECT '{"foo": 10, "bar": [], "baz": {}}'::jsonb #- '{baz}';

这是一个丑陋的黑客,但如果attrB不是您的第一个密钥并且它只出现一次,那么您可以执行以下操作:

UPDATE my_table SET data = REPLACE(data::text, ',"attrB":' || (data->'attrB')::text, '')::json;

While this is certainly easier in 9.5+ using the jsonb operators, the function that pozs wrote to remove multiple keys is still useful.虽然这在 9.5+ 中使用 jsonb 运算符肯定更容易,但 pozs 编写的删除多个键的函数仍然有用。 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+:这是一个使用 jsonb 和 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, (eg in the column "keys" of the table "table_with_keys") you could call this function like this:如果要删除的键存储在表中(例如,在表“table_with_keys”的“键”列中),您可以像这样调用此函数:

SELECT remove_multiple_keys(my_json_object, 
                            VARIADIC (SELECT array_agg(keys) FROM table_with_keys));

One other convenient way of doing this is to use hstore extension.另一种方便的方法是使用 hstore 扩展。 This way you can write some more convenient function to set/delete keys into a json object.通过这种方式,您可以编写一些更方便的函数来将键设置/删除到 json 对象中。 I came up with following function to do the same:我想出了以下功能来做同样的事情:

CREATE OR REPLACE FUNCTION remove_key(json_in json, key_name text)
 RETURNS json AS $$
 DECLARE item json;
 DECLARE fields hstore;
BEGIN
 -- Initialize the hstore with desired key being set to NULL
 fields := hstore(key_name,NULL);

 -- Parse through Input Json and push each key into hstore 
 FOR item IN  SELECT row_to_json(r.*) FROM json_each_text(json_in) AS r
 LOOP
   --RAISE NOTICE 'Parsing Item % %', item->>'key', item->>'value';
   fields := (fields::hstore || hstore(item->>'key', item->>'value'));
 END LOOP;
 --RAISE NOTICE 'Result %', hstore_to_json(fields);
 -- Remove the desired key from store
 fields := fields-key_name;

 RETURN hstore_to_json(fields);
END;
$$ LANGUAGE plpgsql
SECURITY DEFINER
STRICT;

A simple example of use is:一个简单的使用示例是:

SELECT remove_key(('{"Name":"My Name", "Items" :[{ "Id" : 1, "Name" : "Name 1"}, { "Id" : 2, "Name 2" : "Item2 Name"}]}')::json, 'Name');
-- Result
"{"Items": "[{ \"Id\" : 1, \"Name\" : \"Name 1\"}, { \"Id\" : 2, \"Name 2\" : \"Item2 Name\"}]"}"

I have another function to do the set_key operation as well as following:我还有另一个函数来执行 set_key 操作以及以下操作:

CREATE OR REPLACE FUNCTION set_key(json_in json, key_name text, key_value text)
RETURNS json AS $$
DECLARE item json;
DECLARE fields hstore;
BEGIN
 -- Initialize the hstore with desired key value
 fields := hstore(key_name,key_value);

 -- Parse through Input Json and push each key into hstore 
 FOR item IN  SELECT row_to_json(r.*) FROM json_each_text(json_in) AS r
 LOOP
   --RAISE NOTICE 'Parsing Item % %', item->>'key', item->>'value';
   fields := (fields::hstore || hstore(item->>'key', item->>'value'));
 END LOOP;
 --RAISE NOTICE 'Result %', hstore_to_json(fields);
 RETURN hstore_to_json(fields);
END;
$$ LANGUAGE plpgsql
SECURITY DEFINER
STRICT;

I have discussed this more in my blog here.我在我的博客中对此进行了更多讨论。

I was struggling to find a simple update query that removed json keys in Postgres 9.4 without creating a function, so here's an update to @posz answer.我正在努力寻找一个简单的更新查询,该查询在不创建函数的情况下删除了 Postgres 9.4 中的 json 键,所以这里是对 @posz 答案的更新。

UPDATE someTable t
SET someField = newValue
FROM (
    SELECT id,
        json_object_agg(l.key, l.value)::text AS newValue
    FROM someTable t,
        LATERAL (
            SELECT *
            FROM json_each(t.someField::json)
            WHERE "key" <> ALL (ARRAY['key1', 'key2', 'key3'])
        ) AS l
    GROUP BY id
) upd
WHERE t.id = upd.id

Query assumes you have a table like this:查询假设您有一个这样的表:

CREATE TABLE myTable (
    id SERIAL PRIMARY KEY,
    someField text
);

I guess you can use this line from @posz answer instead of json_object_agg line, to make it work on older postgres, but I didn't test it.我想您可以使用@posz 答案中的这一行而不是 json_object_agg 行,使其在较旧的 postgres 上工作,但我没有对其进行测试。

('{' || array_to_string(array_agg(to_json(l.key) || ':' || l.value), ',') || '}')::json AS after

Also make sure to run select from subrequest to make sure you're updating correct data还要确保从子请求中运行 select 以确保更新正确的数据

In my case就我而言

{"size": {"attribute_id": 60, "attribute_name": "Size", "attribute_nameae": "Size" "selected_option": {"option_id": 632, "option_name": "S"}}, "main_color": {"attribute_id": 61, "attribute_name": "Main Color", "selected_option": {"option_id": 643, "option_name": "Red"}}}

Remove size->attribute_nameae删除 size->attribute_nameae

UPDATE table_name set jsonb_column_name = jsonb_set(jsonb_column_name, '{size}', (jsonb_column_name->'size') -  'attribute_namea') WHERE <condition>

In case if you want to remove JSON attribute not only from a single document but also from an array consider using statement like this:如果您不仅要从单个文档而且要从数组中删除 JSON 属性,请考虑使用如下语句:

    UPDATE table_to_update t
    SET jsonColumnWithArray = (SELECT JSON_AGG(jsonItem)
               FROM (SELECT JSON_ARRAY_ELEMENTS(t1.jsonColumnWithArray)::JSONB #- '{customerChange, oldPeriod}' AS jsonItem
                     FROM table_to_update t1
                     WHERE t1.id = t1.id) AS t2);

Input输入

[
  {
    "customerChange": {
      "newPeriod": null,
      "oldPeriod": null
    }
  },
  {
    "customerChange": {
      "newPeriod": null,
      "oldPeriod": null
    }
  }
]

Output输出

[
  {
    "customerChange": {
      "newPeriod": null
    }
  },
  {
    "customerChange": {
      "newPeriod": null
    }
  }
]

I was facing similar issue to remove a key-value pair from an existing json column in postgres.我在从 postgres 的现有 json 列中删除键值对时遇到了类似的问题。 I was able to fix this using - operator as follows:我能够使用-运算符解决此问题,如下所示:

UPDATE my_table
SET data = data::jsonb - 'attrB'
WHERE id = 'A';

If you want to remove a sub-field, like:如果要删除子字段,例如:

{
  "a": {
    "b": "REMOVE ME!"
  }
}

You can simply use:您可以简单地使用:

UPDATE my_table
SET my_json_column = my_json_column::jsonb #- '{a,b}';

For PostgreSQL version > 9.6, you can simply run this:对于 PostgreSQL 版本 > 9.6,您可以简单地运行:

UPDATE my_table 
set data = data::jsonb - 'attrB'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM