Jenny Blunt
Jenny Blunt

Reputation: 1596

Parsing JSON feed with Ruby on Rails

I know this has been covered over and over but I just can't understand how to get started. Am too much of a JSON virgin to know what's going on.

I'm trying to get some data from a json feed on a remote server into a rails3 application.

I understand I need the json gem but I have no idea how to pull the data.

If the url is something like this:

http://my-feed.com/json?res=service&s=table&table=User&start=0&max=5&sort=id&desc=true

How do I go about getting that from my application?

Any help, walk-throughs, tutorials appreciated

Upvotes: 2

Views: 1711

Answers (2)

Brett Bender
Brett Bender

Reputation: 19739

You are going to need to make an HTTP request for the resource, grab the response, and (potentially) parse it yourself - although I think HTTParty will do the JSON parsing for you. HTTParty would be my suggestion for making requests, though.

If you read the README, it links to examples of how to use HTTParty which you should find helpful. The basic example includes how to make a get request, inspect the headers and body, etc. I believe you can also use response.parsed_response to get the parsed response of whatever HTTParty's default parser is. There is also an example of using your own custom parsers (if you prefer another to HTTParty's).

Upvotes: 3

Nils Landt
Nils Landt

Reputation: 3134

I don't really know the json gem - does it only handle the parsing?

If yes, and you only need to pull in the information, try this:

require 'open-uri'

begin
  json = open 'http://my-feed.com/json?res=service&s=table&table=User&start=0&max=5&sort=id&desc=true'
rescue
  # a multitude of HTTP-related errors can occur
end

json_string = json.read
# parse

Upvotes: 3

Related Questions