0

我的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 工作,但我无法找到解决这个问题的方法。请帮忙

4

1 回答 1

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)
于 2020-03-21T10:21:20.740 回答