Skip to content
Advertisement

How to iterate over PostgreSQL jsonb array of objects and modify elements?

Given jsonb array and PostgreSQL 12:

Need to convert it to:

Is it possible somehow to iterate over jsonb array and downcase only “type” values?

I tried:

but it separates data and type pairs into separateelements.

Advertisement

Answer

You need an intermediate level of nesting to rebuild the objects before you aggregate them in the array: for this, you can use a lateral join.

I would also recommend keeping track of the position of each object in the original array, so you can propagate it the the final result – with ordinality comes handy.

Demo on DB Fiddle:

| jsonb_agg                                                                    |
| :--------------------------------------------------------------------------- |
| [{"data": "42", "type": "temperature"}, {"data": "1.1", "type": "pressure"}] |
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement