R:JSON格式处理错误响应(R: Handling error response in JSON

2019-10-21 17:44发布

我请求用户的详细情况Facebook的图形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的错误处理。 比如这个错误响应 (希望没有人会拿这个用户名...)

{
   "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

不过,如果我第一次解析用JSON RCurl我得到的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

Answer 1:

你可以做

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 )VS的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


文章来源: R: Handling error response in JSON format
标签: r json rjsonio