ruby 解析 HTTParty 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8171881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing HTTParty response
提问by Slick23
I'm using HTTParty to pull a list of a Facebook user's books but I'm having trouble parsing the response:
我正在使用 HTTParty 来提取 Facebook 用户的书籍列表,但我在解析响应时遇到了问题:
Facebook returns data this way:
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"
},
And HTTParty parses that into a ruby object. I've tried something like this (where retis the response) ret.parsed_responseand that returns the data array, but actually accessing the items inside returns a method not found error.
HTTParty 将其解析为 ruby 对象。我试过这样的事情(ret响应在哪里)ret.parsed_response并返回数据数组,但实际上访问里面的项目会返回一个方法未找到错误。
This is a sample of what HTTParty actually returns:
这是 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"},
回答by Brett Bender
Do you have any code that is throwing an error? The parsed_responsevariable 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:
你有任何抛出错误的代码吗?parsed_responseHTTParty 响应中的变量是一个哈希值,而不是一个数组。它包含一个键,"data"(字符串,而不是符号)。对于该值"data"在哈希键是散列的数组,所以你会重复这样:
data = ret.parsed_response["data"]
data.each do |item|
puts item["name"]
puts item["category"]
puts item["id"]
# etc
end
回答by Sachin
Just an additional info - It's Not Always a default JSON response
只是一个附加信息 -它并不总是默认的 JSON 响应
HTTParty's result.response.bodyor result.response.parsed_responsedoes notalways have form of a Hash
HTTParty的result.response.body或result.response.parsed_response不不总是有形式哈希
It just depends generally on the headers which you are using in your request. For e.g., you need to specify Acceptheader with application/jsonvalue while hitting GitHub API, otherwise it simply returns as string.
它通常仅取决于您在请求中使用的标头。例如,您需要在点击GitHub API时指定Accept带有application/json值的标头,否则它只是作为字符串返回。
Then you shall have to use JSON.parse(data)for same to convert the string response into Hash object.
然后你必须使用JSON.parse(data)for same 将字符串响应转换为 Hash 对象。

