简体   繁体   中英

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

Using postgres 9.4.

Data:

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

Desired output (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:

[
  {"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.

You can create the JSON value for a single row using:

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:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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