格式化Postgres row_to_json响应以进行查询

时间:2014-07-12 04:52:42

标签: 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\""

我尝试使用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}"

1 个答案:

答案 0 :(得分:1)

您应该使用array_to_jsonarray_agg函数。

例如:

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

它将返回正确的JSON数组

参考文献: