简体   繁体   中英

how to iterate through json result in ruby on rails?

I have a function in ruby on rails, where I make a call and get the following json data. now i want to add another “key”: "value" to each item in the json data and return the new or modified json object from the function. what is the best way to do this in ruby?

def get_results
  results = getJsonData(); 
end 

[
  {    "name" : "Harry Potter",  "rating" : 1,  }, 
  {    "name" : "Lord of the rings",  "rating" : 2,  }, 
  {    "name" : "game of thrones",  "rating" : 3,  }, 
]

You can use map to transform every element of a collection

def get_results
  results = getJsonData(); 
  results.map { |item| item.merge("year" => 2000) }
end 

In this case I'm adding a key "year" to your hashes with value 2000 , it depends what you want to do

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM