Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}, 
like image 206
Slick23 Avatar asked Nov 17 '11 17:11

Slick23


2 Answers

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
like image 85
Brett Bender Avatar answered Nov 01 '22 09:11

Brett Bender


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.

like image 33
Sachin Avatar answered Nov 01 '22 08:11

Sachin