![](/img/trans.png)
[英]Convert array of string to array of Json objects in Postgresql Jsonb
[英]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;
表联系人中的contacts
可以从contactposition
表中分配许多职位。
结果是这样的:
| 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()
和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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.