My database contains a table which has a column withjsonb type, and I want to update a part of these data usingfunctions/operators from postgreSQL. Given we have this:
{ "A":[ {"index":"1"}, {"index":"2"} ], "B":[ {"index":"3"}, {"index":"4"} ]}Let's say we went to add a key with an empty array to objects from "A" array, in order to have:
{ "A":[ {"index":"1", "myArray":[]}, {"index":"2", "myArray":[]} ], "B":[ {"index":"3"}, {"index":"4"} ]}How can I proceed?
I've already tried this kind of things without success:
UPDATE myTable SET myColumn = (myColumn::jsonb)->>'A' || '{"myArray":[]}'UPDATE myTable SET myColumn = ( SELECT jsonb_agg(jsonb_set( element, array['A'], to_jsonb(((element ->> 'A')::jsonb || '{"myArray":[]}')::jsonb) )) FROM jsonb_array_elements(myColumn::jsonb) element)::jsonUPDATE myTable SET myColumn = ( SELECT jsonb_each((element ->> 'A')::jsonb) || '{"myArray":[]}'::jsonb FROM jsonb_array_elements(myColumn::jsonb) element)::jsonObviously, all of these tests have been big failure. I have difficulties to understand how works postgreSQL functions.
Somebody can help?
1 Answer1
The approach withjsonb_array_elements andjsonb_set was the right idea, but somehow you nested them the wrong way round:
UPDATE myTable SET myColumn = jsonb_set(myColumn, '{A}', ( SELECT jsonb_agg( element || '{"myArray":[]}' ) FROM jsonb_array_elements(myColumn -> 'A') element));Btw if your column already hasjsonb data type, you shouldn't need any casts.
6 Comments
json :') so I have included "myColumn" into ato_jsonb() ;)WHERE jsonb_array_length(myColumn -> 'A') > 0;A property that is an array. If that's not the case, yes, you need to add a condition or create the array.jsonb_array_elements function. You can addAS before it to clarify. It ambiguously denotes either the column or the whole single-column relation iirc.Explore related questions
See similar questions with these tags.

