简体   繁体   English

从 postgres 的数组中删除嵌套的 json object

[英]Remove nested json object from array in postgres

I have a json object field in postgres that has the following shape我在 postgres 中有一个 json object 字段,具有以下形状

{
"a": {
   
},
"b": [
    {
        
    }
],
"c": {
    "d": "",
    "e": [
        {
            "id": 1234,
            "f": "",
            "g": ""
        }
    ]
}

} }

I'd like to know how to write a statement that removes object's from e array where the id is 1234 in postgres.我想知道如何编写一个语句,从 postgres 中 id 为 1234 的 e 数组中删除对象。 e could have multiple objects, if there are more than one objects in the e array, I want to keep those and only remove the object with the id of 1234. e 可以有多个对象,如果 e 数组中有多个对象,我想保留这些对象,并且只删除 id 为 1234 的 object。

Thanks谢谢

step-by-step demo:db<>fiddle 分步演示:db<>fiddle

UPDATE t 
SET data = jsonb_set(data::jsonb, '{c,e}', s.new_array::jsonb)::json   -- 4
FROM (
    SELECT
        json_agg(value) as new_array                   -- 3
    FROM
        t,
        json_array_elements(data -> 'c' -> 'e')        -- 1
    WHERE value ->> 'id' != '1234'                     -- 2
) s;
  1. To remove a certain element from a JSON array, you need to expand it into on row per array element要从 JSON 数组中删除某个元素,您需要将其扩展为每个数组元素的一行
  2. Remove the record with the element you want to delete删除包含要删除的元素的记录
  3. Reaggregate the JSON array重新聚合 JSON 阵列
  4. If you want to do an UPDATE on your table, you could use the jsonb_set() function to update the JSON element with your newly created array.如果你想对你的表进行UPDATE ,你可以使用jsonb_set() function 用你新创建的数组更新 JSON 元素。 Unless you are not using type jsonb , you have to case your JSON data into jsonb (and the result back to type json )除非您不使用类型jsonb ,否则您必须将您的 JSON 数据转换为jsonb (并将结果返回类型json

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

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