簡體   English   中英

如何在不創建多維數組的情況下在ROR中創建json對象

[英]How do I create a json object in ROR without it creating a multi-dimensional 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

這是返回的JSON:

[[{"Id":0,"Label":2}], [{"Id":1,"Label":2}]]

然后,如果我想在java腳本中訪問它,我必須執行array[i][0].id來查找id。 當我應該能夠做array[i].id來獲取id。

有什么建議么?

您使用[]構建哈希,必須使用{} 並且不要初始化+ loop + push,這不是慣用的Ruby。 我寫道:

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

@json << {"Id" => x, "Label" => y}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM