user974514
user974514

Reputation: 552

Flattening JSONB array in postgres

I am using Postgres 9.4 and storing my data in as JSONB arrays. I am looking for a way to extract json elements inside the array and replace them with one concatenated json element using psql. Consider as example following table:

'aaa' | [{"a":"foo"},{"b":"bar"},{"c":["baz", 'boom']}]  | 404
'bbb' | [{"bar":"foo"}]                                  | 501

What I am looking to achieve is:

'aaa' | {"a":"foo", "b":"bar", "c":["baz", "boom"]}     | 404
'bbb' | {"bar":"foo"}                                   | 501

I have tried to achieve it using builtin postgres functions for json types. But I only figured out how to extract elements at the exact position. Thanks in advance.

Upvotes: 1

Views: 1340

Answers (1)

Quassnoi
Quassnoi

Reputation: 425371

SELECT  id, jo.obj
FROM    mytable
CROSS JOIN
        LATERAL
        (
        SELECT  JSON_OBJECT_AGG(jt.key, jt.value) obj
        FROM    JSONB_ARRAY_ELEMENTS(data) je
        CROSS JOIN
                LATERAL JSONB_EACH(je.value) jt
        ) jo

Upvotes: 2

Related Questions