【问题标题】:Postgresql JSON using WITH RECURSIVE使用 WITH RECURSIVE 的 Postgresql JSON
【发布时间】:2020-03-21 07:19:57
【问题描述】:

我的json是

[
  {
    "id": null,
    "st": "value1",
    "key": 1,
    "value": "i am calling from",
    "description": null
  },
  {
    "st": "value2",
    "key": 5,
    "value": "i am calling from",
    "description": null
  },

  {
    "id": 25,
    "st": "value3",
    "key": 1,
    "value": "i am calling from",
    "description": null
  }
]

我需要用一个数字迭代 id(仅当它为 null 且没有 id 键时)并形成与下面相同的 json,即使缺少键 (id) 也是如此。它必须是自动 ​​id 生成,因为我永远不知道这个聚合中有多少元素。

[
  {
    "id": 1,
    "st": "value1",
    "key": 1,
    "value": "i am calling from",
    "description": null
  },
  {
    "id": 2,
    "st": "value2",
    "key": 5,
    "value": "i am calling from",
    "description": null
  },
  {
    "id": 25,
    "st": "value3",
    "key": 1,
    "value": "i am calling from",
    "description": null
  }
]

我相信 RECURSIVE CTE 有效,但我无法找到解决此问题的方法。请帮忙

【问题讨论】:

    标签: json common-table-expression postgresql-11 postgresql-12


    【解决方案1】:

    您可以取消嵌套数组并将id 的任何空值替换为数组索引。但是,这并不能保证唯一的 ID,因为可能存在已使用的数组索引。

    select jsonb_agg(
              case 
                when t.d ->> 'id' is null then t.d||jsonb_build_object('id', t.idx)
                else t.d
              end
           )
    from jsonb_array_elements('[
      {
        "id": null,
        "st": "value1",
        "key": 1,
        "value": "i am calling from",
        "description": null
      },
      {
        "st": "value2",
        "key": 5,
        "value": "i am calling from",
        "description": null
      },
      {
        "id": 25,
        "st": "value3",
        "key": 1,
        "value": "i am calling from",
        "description": null
      }
    ]'::jsonb) with ordinality as t(d,idx)
    

    【讨论】:

      猜你喜欢
      • 2014-03-17
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 2021-12-05
      • 2019-03-02
      • 1970-01-01
      • 2019-08-29
      • 2011-03-14
      相关资源
      最近更新 更多