I have a json object field in postgres that has the following shape
{"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. 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.
Thanks
1 Answer1
UPDATE t SET data = jsonb_set(data::jsonb, '{c,e}', s.new_array::jsonb)::json -- 4FROM ( SELECT json_agg(value) as new_array -- 3 FROM t, json_array_elements(data -> 'c' -> 'e') -- 1 WHERE value ->> 'id' != '1234' -- 2) s;- To remove a certain element from a JSON array, you need to expand it into on row per array element
- Remove the record with the element you want to delete
- Reaggregate the JSON array
- If you want to do an
UPDATEon your table, you could use thejsonb_set()function to update the JSON element with your newly created array. Unless you are not using typejsonb, you have to case your JSON data intojsonb(and the result back to typejson)
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
