Arrays 将json对象数组转换为json
在postgres表中,我有一些这种格式的jsonbArrays 将json对象数组转换为json,arrays,json,postgresql,select,unnest,Arrays,Json,Postgresql,Select,Unnest,在postgres表中,我有一些这种格式的jsonb [{"type": "pet", "animal": "cat"}, {"type": "farm", "animal": "cow","colour": "brown"}] {"cat": {"type": "pet", "animal": "cat"}, "cow" {"type": "farm", "animal": "cow", "colour": "brown"} 但我想把它转换成这种格式 [{"type": "pet", "a
[{"type": "pet", "animal": "cat"}, {"type": "farm", "animal": "cow","colour": "brown"}]
{"cat": {"type": "pet", "animal": "cat"}, "cow" {"type": "farm", "animal": "cow", "colour": "brown"}
但我想把它转换成这种格式
[{"type": "pet", "animal": "cat"}, {"type": "farm", "animal": "cow","colour": "brown"}]
{"cat": {"type": "pet", "animal": "cat"}, "cow" {"type": "farm", "animal": "cow", "colour": "brown"}
我想不出来,也找不到互联网上有这种格式的jsonb的人。谁能解决这个问题?理想情况下,没有“color”键/值的数据集不会有{“color”:null},但根本不会有“color”键
我使用的是postgres 9.6,这里有一个选项可以通过取消对json数组的测试并将其重新聚合到一个对象中来实现:
select x.new_js_col
from mytable t
cross join lateral (
select jsonb_object_agg(obj ->> 'animal', to_jsonb(obj)) new_js_col
from jsonb_array_elements(t.js_col) as x(obj)
) x(new_js_col)
这假设您在表mytable
中有一个名为js\u col
的jsonb列
:
| new_js_col |
| :----------------------------------------------------------------------------------------------------- |
| {"cat": {"type": "pet", "animal": "cat"}, "cow": {"type": "farm", "animal": "cow", "colour": "brown"}} |
|新_js_col|
| :----------------------------------------------------------------------------------------------------- |
|{“猫”:{“类型”:“宠物”、“动物”:“猫”},“牛”:{“类型”:“农场”、“动物”:“牛”、“颜色”:“棕色”}|