【问题标题】:Formatting Postgres row_to_json response for query格式化 Postgres row_to_json 响应以进行查询
【发布时间】:2014-07-12 04:52:41
【问题描述】:

我有以下 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}"

【问题讨论】:

  • PostgreSQL 不会像那样返回 json。您可能正在查看访问语言(PHP?)或抽象层(PDO?)的工件
  • @MikeSherrill'CatRecall 有趣。我正在使用红宝石。我会进一步研究。

标签: ruby postgresql postgresql-json


【解决方案1】:

您应该使用array_to_jsonarray_agg 函数。

例如:

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

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

参考资料:

【讨论】:

    猜你喜欢
    • 2014-10-29
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 2020-02-21
    相关资源
    最近更新 更多