24

I'm using HTTParty to pull a list of a Facebook user's books but I'm having trouble parsing the response:

Facebook returns data this way:

{
  "data": [
    {
      "name": "Title", 
      "category": "Book", 
      "id": "21192118877902", 
      "created_time": "2011-11-11T20:50:47+0000"
    }, 
    {
      "name": "Title 2", 
      "category": "Book", 
      "id": "1886126860176", 
      "created_time": "2011-11-05T02:35:56+0000"
    }, 

And HTTParty parses that into a ruby object. I've tried something like this (where ret is the response) ret.parsed_response and that returns the data array, but actually accessing the items inside returns a method not found error.

This is a sample of what HTTParty actually returns:

#<HTTParty::Response:0x7fd0d378c188 @parsed_response={"data"=>
[{"name"=>"Title", "category"=>"Book", "id"=>"21192111877902", "created_time"=>"2011-11-11T20:50:47+0000"},
 {"name"=>"Title 2", "category"=>"Book", "id"=>"1886126860176", "created_time"=>"2011-11-05T02:35:56+0000"},
 {"name"=>"Thought Patterns", "category"=>"Book", "id"=>"109129539157186", "created_time"=>"2011-10-27T00:00:16+0000"},
2
  • 1
    Are you trying like this ret.parsed_response["data"] and ret.parsed_response["data"].first["name"]?
    – rubyprince
    Commented Nov 17, 2011 at 17:54
  • 1
    No ... I was doing ret.parsed_response.data
    – Slick23
    Commented Nov 17, 2011 at 18:02

2 Answers 2

43

Do you have any code that is throwing an error? The parsed_response variable from the HTTParty response is a hash, not an array. It contains one key, "data" (the string, NOT the symbol). The value for the "data" key in the hash is an array of hashes, so you would iterate as such:

data = ret.parsed_response["data"]
data.each do |item|
  puts item["name"]
  puts item["category"]
  puts item["id"]
  # etc
end
1
  • 1
    That was my trouble -- using data the way you've done here. Thanks!
    – Slick23
    Commented Nov 17, 2011 at 18:01
23

Just an additional info - It's Not Always a default JSON response

HTTParty's result.response.body or result.response.parsed_response does not always have form of a Hash

It just depends generally on the headers which you are using in your request. For e.g., you need to specify Accept header with application/json value while hitting GitHub API, otherwise it simply returns as string.

Then you shall have to use JSON.parse(data) for same to convert the string response into Hash object.

Not the answer you're looking for? Browse other questions tagged or ask your own question.