10

I am coding an app that is will be fetching data from different sources around the Internet via their respective API (JSON and XML).

How can I fetch this data (from remote source) and parse it using Rails 3? I looked everywhere on the net for a solution but it all seems very confusing too me.

Do anyone know of a good, simple gem that I can use for remote APIs? It was so simple in PHP.

2 Answers 2

31

Try something like this for JSON

require 'open-uri'
require 'json'

result = JSON.parse(open("url_of_json_service").read)

See more abut the JSON gem here: http://flori.github.com/json/

Try something like this for XML

require 'open-uri'
require 'nokogiri'

result = Nokogiri.XML(open("url_of_xml_service").read)

See more about Nokogiri here: https://github.com/tenderlove/nokogiri (there are other XML parsers)

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you! One more thing. How can I display the results on the front end page? I.e loop through the results in Rails 3?
Assuming the returned data is an array, then a normal ruby each loop should suffice.
It is returned as this: {"created_in":0.046152,"statuses":[40036896721608704,40036681583169536,40036632468004864,40036552943996928,40036376992944128]}
When I try this I get the error: undefined method `statuses' for #<Hash:0xb6d06cac>
I think you better read the Nokogiri documentation for that (it is a little more complex than JSON, but then so is the data format) see nokogiri.org/tutorials
|
1

Savon is a nice gem which will do the work for SOAP based requests(XML). Check out its documentation.

Here is a Railscast for understanding better.

For JSON based requests you can check @DanSingerman answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.