Postgres:以逗号分隔值的行到json对象的数组

时间:2019-04-23 11:24:36

标签: sql json postgresql

使用Postgres 9.4。

数据:

+-----+------+
| id  | type |
+-----+------+
| 1   | A    |
+-----+------+
| 2,3 | A    |
+-----+------+
| 4   | B    |
+-----+------+

所需的输出(JSON)

[
  [{"id": "1", "type": "A"}],
  [{"id": "2", "type": "A"},{"id": "3", "type": "A"}],
  [{"id": "4", "type": "B"}]
]

我尝试过:

SELECT array_to_json(array_agg(c)) 
FROM 
(
  SELECT
    regexp_split_to_table(id, ',') AS id, 
    type 
  FROM my_table
) c;

这使我进入一个简单的json对象数组:

[
  {"id": "1", "type": "A"},
  {"id": "2", "type": "A"},
  {"id": "3", "type": "A"},
  {"id": "4", "type": "B"}]
]

如何将子查询的每个结果集(而不是每一行)包装在一个数组中?

2 个答案:

答案 0 :(得分:2)

我相信这可以满足您的需求

with t as (
      select *
      from (values ('1', 'A'), ('2,3', 'A'), ('4', 'B')) v(ids, type)
     )
select json_agg(c)
from (select array_to_json(array_agg( json_build_object('id', c.id, 'type', c.type))) as c
      from (select ids, regexp_split_to_table(ids, ',') AS id, type 
            from t
           ) c
      group by ids
     ) i;

Here是db <>小提琴。

答案 1 :(得分:0)

您可以使用以下方法为单行创建JSON值:

select (select json_agg(to_json(t)) 
        from (
          select i.id, t.type 
          from unnest(string_to_array(t.ids, ',')
        ) as i(id)) t) json_id
from the_table t

您可以将其包装到派生表中,以将所有内容聚合为一个JSON值:

select json_agg(json_id)
from (
  select (select json_agg(to_json(t)) 
          from (select i.id, t.type from unnest(string_to_array(t.ids, ',')) as i(id)) t) json_id
  from the_table t
) x;