我有以下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}"
答案 0 :(得分:1)
您应该使用array_to_json
和array_agg
函数。
例如:
SELECT array_to_json(array_agg(row_to_json(row))) FROM ...
它将返回正确的JSON数组
参考文献: