Postgresql – Update all the elements of JSON array nested in a JSON column (Postgres)

postgresqlpostgresql-9.6

I have json column with data that looks like this:

{
    a: [
        { q: 5 },
        { q: 8 },
        { q: 10 }
    ]
}

I'd like to map over the elements in the array and add an extra property to get something like this:

{
    a: [
        { q: 5, r: [] },
        { q: 8, r: [] },
        { q: 10, r: [] }
    ]
}

Any and all would be greatly appreciated.

PostgreSQL 9.6.6

Best Answer

I think I worked it out. Something like:

SELECT my_column::jsonb ||
    jsonb_build_object('a',
            (SELECT json_agg(a::jsonb || jsonb_build_object('r','[]'::jsonb))
            FROM jsonb_array_elements(my_column->'a') a)
    )
FROM my_table;

Though this might not be perfect since I'm translating to this example without testing.