Ruby 将Postgres行\u格式化为\u查询的json响应
我有以下Postgres查询:Ruby 将Postgres行\u格式化为\u查询的json响应,ruby,postgresql,postgresql-json,Ruby,Postgresql,Postgresql Json,我有以下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\"
"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\""
我试图使用行到行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}"}
但是,我并不真正希望响应嵌套在行到\u json
散列中。有没有一种简单的方法可以删除它,所以我只需返回:
"{\"index\":1,\"created_at\":\"2014-07-12 03:51:00\",\"numeric\":3}"
您应该使用
array\u to\u json
和array\u agg
函数
例如:
SELECT array_to_json(array_agg(row_to_json(row))) FROM ...
它将返回正确的JSON数组
参考资料: