Interfacing with a third-party API in Rails? ( Opeing URLs and Parsing XML/JSON ) Interfacing with a third-party API in Rails? ( Opeing URLs and Parsing XML/JSON ) xml xml

Interfacing with a third-party API in Rails? ( Opeing URLs and Parsing XML/JSON )


for opening urls you can use open-uri

just

require 'open-uri'file_handle = open("http://google.com/blah.xml")

to parse xml you can use Nokogiri

$ gem install nokogiri

document = Nokogiri::XML(file_handle)document/"xpath/search"

very powerful library, can do all kinds of searching and modifying for both XML and HTML

same for html Nokogiri::HTML

there is also lots of JSOM support out there too

checkout Nokogiri also Hpricot is good for XML/HTML

for JSON in rails

parsed_json = ActiveSupport::JSON.decode(your_json_string)parsed_json["results"].each do |longUrl, convertedUrl|  site = Site.find_by_long_url(longUrl)  site.short_url = convertedUrl["shortUrl"]  site.saveend

see this question:How do I parse JSON with Ruby on Rails?


In a perfect world, a gem already exists for the API you want to use, and you would just use that. Otherwise, you have a few options:

Parsing JSON is generally very straightforward. For XML, as stated in another answer, Nokogiri is probably the way to go.