我正在使用HTTParty提取Facebook用户的书籍 list ,但无法解析响应:
Facebook以这种方式返回数据:
{
"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"
},
HTTParty将其解析为ruby对象。我已经尝试过类似这样的操作(其中
ret
是响应)ret.parsed_response
,它返回数据数组,但实际上访问其中的项将返回方法未找到错误。这是HTTParty实际返回的示例:
#<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"},
最佳答案
您是否有任何引发错误的代码? HTTParty响应中的parsed_response
变量是哈希,而不是数组。它包含一个键"data"
(字符串,不是符号)。哈希中"data"
键的值是一个哈希数组,因此您将这样迭代:
data = ret.parsed_response["data"]
data.each do |item|
puts item["name"]
puts item["category"]
puts item["id"]
# etc
end