Alin Mechenici

Parsing JSON with Ruby

Parsing JSON with Ruby is actually extremely easy. All you have to do is have the json gem installed (gem install json) and call the JSON.parse method on the JSON data to convert it to ruby hashes. If you look at this small program here, you can see how I have implemented parsing JSON in Ruby.

#!/usr/bin/env rubyrequire'json'require'net/http'require'libnotify'defparsejsonfile="http://api.openweathermap.org/data/2.5/find?q=London&mode=json"response=Net::HTTP.get_response(URI.parse(file))weatherjson=response.bodyactual=JSON.parse(weatherjson)# check for errorsifactual.has_key?'Error'raise"error with the url"endresults=[]actual["list"].eachdo|listitem|weather=listitem["weather"]weather.eachdo|weath|results.push(weath["description"])endmain=listitem["main"]temp=main["temp"]-273.15results.push("%.2f"%temp)endreturnresultsend