Flattening JSONB array in postgres

北战南征 提交于 2020-01-14 04:52:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!