mirror of
https://github.com/aljazceru/cryptoanarchywiki.github.io.git
synced 2025-12-17 05:04:21 +01:00
Pertamax
This commit is contained in:
41
_posts/2013-12-23-ruby-json.markdown
Normal file
41
_posts/2013-12-23-ruby-json.markdown
Normal file
@@ -0,0 +1,41 @@
|
||||
---
|
||||
layout: post
|
||||
title: "Parsing JSON with Ruby"
|
||||
date: 2013-12-23 00:18:23
|
||||
categories: 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 %}
|
||||
Reference in New Issue
Block a user