I have a database table called menu_items
which contains a jsonb[]
field called build_items
. Inside the build_items
array is an objects with a field called item_id
that I need to rename to value
.
I found this post (PostgreSQL rename attribute in jsonb field), which describes my problem, except that I need it to work for each element in an array.
Is this operation possible using only PostgreSQL or do I need to write some code to pull the data, alter it, then update the table?
I also tried converting the jsonb[]
to TEXT
and performing a REPLACE
, then attempting to convert it back to a jsonb[]
value. The result (in query form) is correct, but I'm not sure how I would use the results to update the correct rows in menu_items
.
SELECT jsonb_agg(temp.data) AS result
FROM (SELECT json_array_elements(REPLACE(array_to_json(build_items)::TEXT, 'item_id', 'value')::json) AS data
FROM menu_items
WHERE build_items IS NOT NULL) temp;