【问题标题】:R: Handling error response in JSON formatR:处理 JSON 格式的错误响应
【发布时间】:2015-02-01 01:53:15
【问题描述】:

我正在向 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管理错误吗?

【问题讨论】:

    标签: r json rjsonio


    【解决方案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)与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
    

    【讨论】:

      猜你喜欢
      • 2016-05-20
      • 2015-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多