簡體   English   中英

Postgres:以逗號分隔值的行到json對象的數組

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

使用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"}]
]

如何將子查詢的每個結果集(而不是每一行)包裝在數組中?

我相信這可以滿足您的需求:

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;

是db <>小提琴。

您可以使用以下方法為單行創建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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM