Search code examples
rubyfacebook-graph-api

Parsing HTTParty response


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"},

Solution

  • 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