Parse JSON using Ruby

JSON, or JavaScript Object Notation, is a lightweight data interchange format. JSON data maps easily to data structures in most of the modern programming languages. Many of Yahoo!'s Web Service APIs optionally provide you with JSON output, simply by appending a output=json to your query string.

JSON Libraries for Ruby

The following example shows how to parse JSON data in Ruby. We'll use the JSON library for Ruby available here for the same. It is available as a gem, so installation is straightforward:

gem install json

Example: News Search

require 'rubygems'
require 'json'
require 'net/http'

def news_search(query, results=10, start=1)
   base_url = "http://search.yahooapis.com/NewsSearchService/V1/newsSearch?appid=YahooDemo&output=json"
   url = "#{base_url}&query=#{URI.encode(query)}&results=#{results}&start=#{start}"
   resp = Net::HTTP.get_response(URI.parse(url))
   data = resp.body

   # we convert the returned JSON data to native Ruby
   # data structure - a hash
   result = JSON.parse(data)

   # if the hash has 'Error' as a key, we raise an error
   if result.has_key? 'Error'
      raise "web service error"
   end
   return result
end

Usage of the above:

irb(main):001:0> require 'ruby-json'
=> true
irb(main):002:0> news = news_search('ruby', 2)
=> [...]
irb(main):003:0> news['ResultSet']['Result'].each { |result|
irb(main):004:1* print "#{result['Title']} => #{result['Url']}\n"
irb(main):005:1> }
Sun, Ruby, and Java: An Interesting Turn of Events => http://www.linuxjournal.com/node/1000091
BBEdit 8.5 a?ade soporte de Ruby y mejoras de interfaz => http://www.idg.es/macworld/content.asp?idn=50291
=> [...]
irb(main):006:0>

Each result is a Ruby hash containing a number of keys.

Further reading

Yahoo Forum Discussions