mirror of
https://github.com/aljazceru/cryptoanarchywiki.github.io.git
synced 2025-12-17 13:14:21 +01:00
1.1 KiB
1.1 KiB
layout, title, date, categories
| layout | title | date | categories |
|---|---|---|---|
| post | Parsing JSON with Ruby | 2013-12-23 00:18:23 +0700 | 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.
{% highlight ruby %} #!/usr/bin/env ruby
require 'json' require 'net/http' require 'libnotify'
def parsejson file = "http://api.openweathermap.org/data/2.5/find?q=London&mode=json" response = Net::HTTP.get_response(URI.parse(file)) weatherjson = response.body actual = JSON.parse(weatherjson)
# check for errors
if actual.has_key? 'Error'
raise "error with the url"
end
results = []
actual["list"].each do |listitem|
weather = listitem["weather"]
weather.each do |weath|
results.push(weath["description"])
end
main = listitem["main"]
temp = main["temp"] - 273.15
results.push ("%.2f" % temp)
end
return results
end {% endhighlight %}