将json对象数组转换为json

数据库守护者

在postgres表中,我有一些这种格式的jsonb

[{"type": "pet", "animal": "cat"}, {"type": "farm", "animal": "cow","colour": "brown"}]

但是我想把它变成这种格式

{"cat": {"type": "pet", "animal": "cat"}, "cow" {"type": "farm", "animal": "cow", "colour": "brown"}

而且我无法弄清楚,也找不到互联网上有人使用这种格式的jsonb。谁能解决这个问题?理想情况下,没有“颜色”的键/值的数据集将没有{“颜色”:空},但根本没有键“颜色”

我在使用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)

假设您有一个js_col在table中调用的jsonb列mytable

DB Fiddle上的演示

| new_js_col | 
| :------------------------------------------------- -------------------------------------------------- -| 
| {“ cat”:{“ type”:“ pet”,“ animal”:“ cat”},“ cow”:{“ type”:“ farm”,“ animal”:“ cow”,“ colour”:“ brown” “}} |

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章