R: Handling error response in JSON format

2019-08-15 17:09发布

问题:

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"   

All good.

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
   }
}

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

I get

Error in file(con, "r") : cannot open the connection

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

It is possible to manage the error directly with RJSONIO?

回答1:

You can do

result <- try(RJSONIO::fromJSON("http://graph.facebook.com/?ids=this.username.does.not.exist.because.i.made.it.up"), 
              silent=TRUE)`

and check class(result) before processing (it will be try-error if you get the error you posted).

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 rjsonio