开发者

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&sor开发者_运维问答t=id&desc=true

How do I go about getting that from my application?

Any help, walk-throughs, tutorials appreciated


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).


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜