Created
March 11, 2012 20:23
-
-
Save danlmyers/2018071 to your computer and use it in GitHub Desktop.
Example for the rubygem Json parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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