I am using postgres 12.X, I have the following logs table :-
logs
id bigint ,jsondata text
Following are values in json
[ { "loginfo": "somelog1", "id": "app1" },{ "loginfo": "somelog2", "id": "app2" } ]I need remove all json objects from this text column where id == "app2"
tried the below as per answer here :-https://dba.stackexchange.com/questions/84472/how-to-remove-object-from-json-array
UPDATE logs i SET jsondata = i2.jsondata FROM (SELECT id, array_to_json(array_agg(elem)) AS jsondata FROM logs cand , json_array_elements(cand.jsondata) elem WHERE cand.jsondata @> '{[{"id":"app2"}]}'::jsonb AND elem->>'id' <> 'app2' GROUP BY 1 ) i2WHERE i2.id = i.id;But ERROR comes as below :-
ERROR: function json_array_elements(text) does not exist
- Your column is no defined as
jsonb(or at leastjson) so you need to cast it, e.g.json_array_elements(jsondata::json)- the best solution is to change its data type fromtexttojsonbusingalter table(and then use the jsonb_xxxx functions)user330315– user3303152021-03-09 10:34:51 +00:00CommentedMar 9, 2021 at 10:34 - 2Don't abuse JSON like this. Store these data in a separate table without JSON columns and have a foreign key relationship between the tables. Then the exercise becomes trivial.Laurenz Albe– Laurenz Albe2021-03-09 10:35:16 +00:00CommentedMar 9, 2021 at 10:35
1 Answer1
Why do you store JSON objects intext columns? In that case you need to cast it before using it as JSON:
SELECT id, json_agg(elems) -- 3FROM mytable, json_array_elements(jsondata::json) as elems -- 1WHERE elems ->> 'id' <> 'app2' -- 2GROUP BY id- Cast text into JSON; Extract the JSON array into a record per element
- Filter the required objects
- Reaggregate remaining elements into a new JSON array
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
