问题
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:
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
来源:https://stackoverflow.com/questions/36704489/flattening-jsonb-array-in-postgres