I have a jsonb structure in PostgreSQL 9.6 that contains a nested array structure similar to the example below:
continents:[
{
id: 1,
name: 'North America',
countries: [
{
id: 1,
name: 'USA',
subdivision: [
{
id: 1,
name: 'Oregon',
type: 'SOME_TYPE'
}
]
}
]
}
]
How can I change the 'type' attribute of multiple subdivisions since it its nested within two arrays ( countries and subdivision )?
I've come across other answers and am able to do so on a record by record basis (assuming table is map and jsonb column is divisions ):
update map
set divisions = jsonb_set( divisions, '{continents,0,countries,0,subdivisions,0,type}', '"STATE"', FALSE);
Is there a way to programatically change that attribute for all subdivisions?
I think I'm getting close, I can query all subdivision types using the query below, but am struggling to figure out how to update them:
WITH subdivision_data AS (
WITH country_data AS (
select continents -> 'countries' as countries
from map, jsonb_array_elements( map.divisions -> 'continents' ) continents
)
select country_item -> 'subdivisions' as subdivisions
from country_data cd, jsonb_array_elements( cd.countries ) country_item
)
select subdivision_item ->> 'type' as subdivision_type
from subdivision_data sub, jsonb_array_elements( sub.subdivisions ) subdivision_item;
Here's some of the questions I came across. They seem to work only if you are trying to update a single level array though:
postgresql 9.5 using jsonb_set for updating specific jsonb array value
How to update deeply nested JSON object based on filter criteria in Postgres?