在Postgres中展平JSONB数组 [英] Flattening JSONB array in postgres
本文介绍了在Postgres中展平JSONB数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Postgres 9.4并将数据存储为JSONB数组.我正在寻找一种方法来提取数组内的json元素,并使用psql将它们替换为一个串联的json元素.以下表为例:
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
我想要实现的是:
'aaa' | {"a":"foo", "b":"bar", "c":["baz", "boom"]} | 404
'bbb' | {"bar":"foo"} | 501
我尝试使用内置的json类型的postgres函数来实现它.但是我只想出了如何在确切位置提取元素. 提前致谢.
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.
推荐答案
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
这篇关于在Postgres中展平JSONB数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文