我正在运行一个包含4列作为输出的select语句。是否可以将它们分组为一组字典?
这是我的陈述:
select users.id as user_id,
subscriptions.id as subscription_id,
subscriptions.latest_receipt as receipt,
users.status as users_status
from users,subscriptions
where users.subscription_id = subscriptions.id;
我可以为数组使用array_constructor。我试图将每个输出合并为字典并将其添加到数组中。
所需的输出将是:
[{'userid':'1','subscriptionid':'18783278237','receipt':'3AHD83...KJ$@','status':'2'},{'userid':'2','subscriptionid':'18233273435','receipt':'3HJSD3...K*&#K','status':'2'}]
答案 0 :(得分:1)
您可以使用row_to_json()
和json_agg()
:
select json_agg(row_to_json(x))
from (
select users.id as userid,
subscriptions.id as subscriptionid,
subscriptions.latest_receipt as receipt,
users.status as status
from users
join subscriptions on users.subscription_id = subscriptions.id
) x
必须使用派生表将列名作为属性名称保存在JSON文档中。我还使用明确的WHERE
运算符替换了JOIN
子句中古老的,过时的和脆弱的隐式连接。
如果您需要将结果作为纯文本值处理,可以使用json_agg(row_to_json(x))::text