如何将散列与数组组合并将结果显示为 json

How to combine hash with an array and display result as json

我试图在不同的 SQL 查询后显示 json。一些 SQL 查询 return 一个值,但我从其中一个查询中得到了一组结果。您可以在下面看到我要显示的 json 的示例。

{
"id": "4",
"potential": "23",
"conversion": "45",
"new": "34",
"repeat": "22",
"average": "14",
"traffic": [
  {
  "time": "9",
  "new": "2",
  "repeat": "1"
  },
  {
  "time": "10",
  "new": "6",
  "repeat": "9"
  }
 ]
}

我可以将散列和数组单独显示为 json,但是我不能将它们组合起来。

{
"id": "4",
"potential": "23",
"conversion": "45",
"new": "34",
"repeat": "22",
"average": "14"
}

AND

[
{
"time": 5,
"new": 0,
"repeat": 80
},
{
"time": 6,
"new": 1,
"repeat": 80
}
]

有什么建议吗?谢谢

遍历你得到的响应并将数据添加到Hash。这是它的 ruby-doc。如果您需要了解如何使用哈希,请参阅下面的代码。

x = {"id" => "4", "potential" => "23","conversion"=> "45","new"=> "34","repeat"=> "22","average"=> "14"}
x["traffic"] =[{"time"=>5,"new"=>0,"repeat"=>80},{"time"=>6,"new"=>1,"repeat"=>80}]

您将不得不使用您的逻辑来构建哈希。我刚刚为你写了一些东西。你也可以 return 通过 render :json => x.

的散列