gpt4 book ai didi

ruby - 格式化查询的 Postgres row_to_json 响应

转载 作者:行者123 更新时间:2023-11-29 13:30:32 25 4
gpt4 key购买 nike

我有以下 Postgres 查询:

"SELECT \"responses\".\"index\", \"responses\".\"created_at\",
ROUND(AVG(\"responses\".\"numeric\")) AS numeric
FROM \"responses\"
WHERE \"responses\".\"time\" = '#{time}'
GROUP BY \"responses\".\"index\", \"responses\".\"created_at\""

我正在尝试使用 row_to_json 将响应输出为 json。我可以使用:

"select row_to_json(row)
from (
SELECT \"responses\".\"index\", \"responses\".\"created_at\",
ROUND(AVG(\"responses\".\"numeric\")) AS numeric
FROM \"responses\"
WHERE \"responses\".\"time\" = '#{time}'
GROUP BY \"responses\".\"index\", \"responses\".\"created_at\"
) row"

这会给我:

{"row_to_json"=>"{\"index\":1,\"created_at\":\"2014-07-12 03:51:00\",\"numeric\":3}"}

但是我真的不想将响应嵌套在 row_to_json 哈希中。有没有一种简单的方法可以删除它,所以我只返回:

"{\"index\":1,\"created_at\":\"2014-07-12 03:51:00\",\"numeric\":3}"

最佳答案

您应该使用 array_to_jsonarray_agg 函数。

例如:

SELECT array_to_json(array_agg(row_to_json(row))) FROM ...

它将返回一个正确的 JSON 数组

引用资料:

关于ruby - 格式化查询的 Postgres row_to_json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24709785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com