1

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.

1 Answer 1

2
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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.