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

pri*_*moz 1 python sql postgresql json jsonb

我在使用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;
Run Code Online (Sandbox Code Playgroud)

表中的联系人contacts可以从表中分配许多职位contactposition

结果是这样的:

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

但是我希望它是这样的:

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

我知道一些辅助功能,例如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;
Run Code Online (Sandbox Code Playgroud)

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

我将不胜感激,谢谢!

kli*_*lin 5

使用jsonb_build_object()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;
Run Code Online (Sandbox Code Playgroud)