I need some help to update elements in a JSON array. I want to update each element in a JSON array based on the value of a parameter.
The table has 2 columns: id (bigint NOT NULL GENERATED ALWAYS AS IDENTITY) and dashnoard (jsonb).
Here the JSON stored in the column dashboard:
[
{
"role": "A",
"state": "running",
"reference": "1234"
},
{
"role": "B",
"state": "iddle",
"reference": "1235"
}
]
My request:
WITH items AS (
SELECT ('{'||index-1||',state}')::TEXT[] AS path
FROM my_table, jsonb_array_elements_text(dashboard) WITH ORDINALITY arr(item, index)
WHERE (item::JSONB->>'state' = 'iddle' OR item::JSONB->>'state' = 'running') AND id=5
)
UPDATE my_table
SET dashboard = jsonb_set(dashboard, items.path, '"canceled"', false)
FROM items
WHERE id=5;
What I want : all (here the 2) elements of the JSON array with state in ('running', 'iddle') updated with state := 'canceled'
What I have : only the first element of the JSON array updated with state := 'canceled'. The second stay unchange.
Thank you