2011-12-27 110 views
2

我需要從JSON響應中創建一個自動完成的映射/數組,我正在尋找最好的,最有效的方法來在Ruby和Rails 3中完成它。響應的一部分在下面,我有工作代碼在它之前。我需要爲我創建位置的一行代碼是什麼?從API如何在Ruby on Rails 3中從JSON響應創建映射?

# Need help making this more efficient 
response_fields = JSON.parse(response.body) 
predictions = response_fields['predictions'] 
predictions.each do |prediction| 
    locations << prediction['description'] 
end 

樣本響應:

{ 
    "predictions" : [ 
    { 
     "description" : "Napa, CA, United States", 
     "id" : "cf268f9fb9a1b46aed72d59ab85ed40f982763c6", 
     "matched_substrings" : [ 
      { 
      "length" : 4, 
      "offset" : 0 
      } 
     ], 
    "reference" : "CjQvAAAAqZWNGzqtJf3awNuQNQdnZpl4dBVVXFPrPdz29r1jo1GMWYFuz3KRlK9HgdgszOThEhDeYz_vYgcOPJTaYehF11bUGhR8yH9zqMGV9kenZIo9OTBrSwftgg", 
    "terms" : [ 
     { 
      "offset" : 0, 
      "value" : "Napa" 
     }, 
     { 
      "offset" : 6, 
      "value" : "CA" 
     }, 
     { 
      "offset" : 10, 
      "value" : "United States" 
     } 
    ], 
    "types" : [ "locality", "political", "geocode" ] 
    }, 

回答

4

您可以縮短你這樣的代碼:

locations = JSON.parse(response.body)['predictions'].map { |p| p['description'] }