R:以JSON格式处理错误响应

时间:2015-02-01 01:53:16

标签: r json rjsonio

我正在向Facebook Graph API请求用户详细信息,例如

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处理错误。例如this error response(希望没有人会使用此用户名......)

{
   "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解析它

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格式的错误消息

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

管理错误

1 个答案:

答案 0 :(得分:3)

你可以做到

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。)

您还可以使用httr包(直接使用RSJSONIO包的现代分支 - jsonlite)与RJSONIO包:

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