R:处理JSON格式的错误响应 [英] R: Handling error response in JSON format
问题描述
我正在向Facebook Graph API请求用户详细信息,例如
I am requesting user details to the Facebook Graph API, such as
require(RJSONIO)
response <- RJSONIO::fromJSON("http://graph.facebook.com/?ids=Jack")
print(response)
# $Jack
# id first_name gender last_name locale
# "534213341" "Jack" "male" "Lindamood" "en_US"
# name username
# "Jack Lindamood"
一切都很好.
但是有时我会从API处理一个错误.例如此错误响应(希望没有人会使用此用户名...)
But then sometime I have an error from the API to handle. Such as this error response (hope nobody will take this username...)
{
"error": {
"message": "(#803) Some of the aliases you requested do not exist: this.username.does.not.exist.because.i.made.it.up",
"type": "OAuthException",
"code": 803
}
}
如果我尝试使用RJSONIO对其进行解析
If I try to parse it with RJSONIO
RJSONIO::fromJSON("http://graph.facebook.com /?ids=this.username.does.not.exist.because.i.made.it.up")
我知道
Error in file(con, "r") : cannot open the connection
但是如果我先用RCurl
解析json,我会得到rjson格式的错误消息
But then If I first parse the json with RCurl
I get the rjson-formatted error message
require(RCurl)
json <- getURL("http://graph.facebook.com/?ids=this.username.does.not.exist.because.i.made.it.up")
RJSONIO::fromJSON(json)
$error
$error$message
[1] "(#803) Some of the aliases you requested do not exist: this.username.does.not.exist.because.i.made.it.up"
$error$type
[1] "OAuthException"
$error$code
[1] 803
是否可以直接使用RJSONIO
管理错误?
It is possible to manage the error directly with RJSONIO
?
推荐答案
您可以
result <- try(RJSONIO::fromJSON("http://graph.facebook.com/?ids=this.username.does.not.exist.because.i.made.it.up"),
silent=TRUE)`
并在处理前检查class(result)
(如果收到所发布的错误,将为try-error
).
and check class(result)
before processing (it will be try-error
if you get the error you posted).
相对于RJSONIO
包,您还可以使用httr
包(直接使用RSJSONIO
包的现代分叉-jsonlite
):
You could also use the httr
package (which directly uses a modern fork of the RSJSONIO
package - jsonlite
) vs the RJSONIO
package:
library(httr)
content(GET("http://graph.facebook.com/?ids=Jack"), as="parsed")
content(GET("http://graph.facebook.com/?ids=this.username.does.not.exist.because.i.made.it.up"),
as="parsed")
## $error
## $error$message
## [1] "(#803) Some of the aliases you requested do not exist: this.username.does.not.exist.because.i.made.it.up"
##
## $error$type
## [1] "OAuthException"
##
## $error$code
## [1] 803
这篇关于R:处理JSON格式的错误响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!