简体   繁体   English

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

[英]Postgres: row with comma separated value to array of json objects

Using postgres 9.4. 使用Postgres 9.4。

Data: 数据:

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

Desired output (JSON): 所需的输出(JSON):

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

I've tried: 我试过了:

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

which gets me to a simple array of json objects: 这使我进入一个简单的json对象数组:

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

How do I wrap each resultset (not each row) of the subquery in an array? 如何将子查询的每个结果集(而不是每一行)包装在数组中?

I believe this does what you want: 我相信这可以满足您的需求:

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 is a db<>fiddle. 是db <>小提琴。

You can create the JSON value for a single row using: 您可以使用以下方法为单行创建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

you can wrap that into a derived table to aggregate everything to a single JSON value: 您可以将其包装到派生表中,以将所有内容聚合为一个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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM