【问题标题】:Convert array of json objects into json将 json 对象数组转换为 json
【发布时间】:2020-10-02 10:24:16
【问题描述】:

在 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 的人。谁能解决这个问题?理想情况下,没有“颜色”键/值的数据集不会有 {“color”:null},但根本没有“颜色”键

我在 postgres 9.6

【问题讨论】:

    标签: arrays json postgresql select unnest


    【解决方案1】:

    这是一种通过取消嵌套 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_col 的 jsonb 列。

    Demo on DB Fiddle:

    | new_js_col | | :------------------------------------------------ -------------------------------------------------- -- | | {“猫”:{“类型”:“宠物”,“动物”:“猫”},“牛”:{“类型”:“农场”,“动物”:“牛”,“颜色”:“棕色” "}} |

    【讨论】:

      猜你喜欢
      • 2012-07-21
      • 1970-01-01
      • 2018-10-11
      • 2018-04-16
      • 2018-09-12
      • 2015-10-30
      • 1970-01-01
      相关资源
      最近更新 更多