Javascript 如何在ROR中创建json对象而不创建多维数组

Javascript 如何在ROR中创建json对象而不创建多维数组,javascript,ruby-on-rails,ruby,json,Javascript,Ruby On Rails,Ruby,Json,举个例子,如果我试图创造这样的东西 @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 然后,如果我想在java脚本中访问它,我必须执行array[

举个例子,如果我试图创造这样的东西

@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
然后,如果我想在java脚本中访问它,我必须执行
array[I][0].id
来查找id。当我应该能够执行
array[I].id
来获取id时


有什么建议吗?

如何执行
@json x,“Label”=>y}

您使用
[]
构建哈希,必须使用
{}
。不要初始化+循环+推送,这不是惯用的Ruby。我会写:

@json = (0..1).map { |id| {"Id" => id, "Label" => 2} }
#=> [{"Id"=>0, "Label"=>2}, {"Id"=>1, "Label"=>2}]

我发现Ruby在这种特殊情况下有点困惑。Imho
[“Id”=>x,“Label”=>y]
应该抛出异常,而不是将其转换为包含哈希的列表。@freakish:这是一个功能,因此您可以以紧凑的方式编写哈希数组。老实说,我也不喜欢。如果你想写
.id
为什么要用upcase
id
来构建散列呢?
@json = (0..1).map { |id| {"Id" => id, "Label" => 2} }
#=> [{"Id"=>0, "Label"=>2}, {"Id"=>1, "Label"=>2}]