在 Postgresql 中将记录数组转换为 JSON

Convert array of records to JSON in Postgresql

我在使用 Postgresql 将记录数组转换为 JSON 时遇到问题。

版本: psql (PostgreSQL) 9.5.3

当前查询:

SELECT c.id, (select array(
        select (cp.id,cp.position)
        from contactposition cp
        where cp.contact_id_id = c.id  -- join on the two tables
        )
      ) as contactpositions
from contacts c;

来自 table contacts 的联系人可以从 contactposition table.

分配多个职位

结果是这样的:

| id (integer) | contactpositions (record[])                                          |
|--------------|----------------------------------------------------------------------|
| 5            | {"(21171326,\"Software Developer\")","(21171325,Contractor)" (...)"} |

但我希望它是这样的:

| id (integer) | contactpositions (record[])                                          |
|--------------|----------------------------------------------------------------------|
| 5            | [{"id": 21171326, "position": "Software Developer", "id": 21171325, "position": "Contractor", (...)] |

我知道有几个辅助函数,例如 array_to_json,但我就是无法使用它。

我试过:

SELECT c.id, array_to_json(select array(
            select (cp.id,cp.position)
            from contactposition cp
            where cp.contact_id_id = c.id
            )
          ) as contactpositions
from contacts c;

但它抛出:ERROR: syntax error at or near "select",所以显然我没有正确使用它。

如果有任何提示,我将不胜感激!

使用jsonb_build_object() and jsonb_agg():

select c.id, jsonb_agg(jsonb_build_object('id', cp.id, 'position', cp.position))
from contacts c
join contactposition cp on c.id = cp.contact_id
group by 1;