Skip to content

Instantly share code, notes, and snippets.

@danlmyers
Created March 11, 2012 20:23
Show Gist options
  • Save danlmyers/2018071 to your computer and use it in GitHub Desktop.
Save danlmyers/2018071 to your computer and use it in GitHub Desktop.
Example for the rubygem Json parsing
#!/usr/bin/env ruby
#Simple example of using json ruby gem.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment