例如,如果我尝试创建这样的东西
@json = Array.new
for x in 0..1
y = 2
@json << ["Id" => x, "Label" => y]
end
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @nodes }
end
这是返回的 JSON:
[[{"Id":0,"Label":2}], [{"Id":1,"Label":2}]]
然后如果我想在 java 脚本中访问它,我必须执行 array[i][0].id
来找到 id。当我应该能够执行 array[i].id
来获取 id 时。
有什么建议吗?
最佳答案
您使用 []
构建哈希,您必须使用 {}
。并且不要初始化 + 循环 + 推送,这不是惯用的 Ruby。我会写:
@json = (0..1).map { |id| {"Id" => id, "Label" => 2} }
#=> [{"Id"=>0, "Label"=>2}, {"Id"=>1, "Label"=>2}]
关于javascript - 如何在不创建多维数组的情况下在 ROR 中创建 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10724657/