Agus Makmun

I'm Programmer for Python & Django. I've made quite a few web apps, especially on Django.

Parsing JSON with Ruby

22 Dec 2013 » 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 ruby

require 'json'
require 'net/http'
require 'libnotify'

def parsejson
    file = ""
    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"

    results = []

    actual["list"].each do |listitem|
        weather = listitem["weather"]
        weather.each do |weath|
        main = listitem["main"]
        temp = main["temp"] - 273.15
        results.push ("%.2f" % temp)

    return results