解析错误:在fromJSON()中打开错误URL时过早EOF

  • 本文关键字:错误 URL EOF fromJSON r
  • 更新时间 :
  • 英文 :


这个语句给了我一个错误。

somevar <- fromJSON('https://www.predictit.org/api/Public/GetMarketChartData/99999?timespan=90d&maxContracts=9999&showHidden=true')
Error in parse_con(txt, bigint_as_char) : parse error: premature EOF

(right here) ------^

我如何设置这样,如果有一个错误,我的R脚本可以处理它没有崩溃?相反,如果fromJSON()遇到打开URL的错误,我希望somevar成为空白字符串或FALSE

我通常是这样做的,如果(a)没有连接到服务器或文件,但(b1)如果有连接到文件,则安全地获得空json(即list()),但结果是一个不可读/格式化的json。实现purrr的safely()possibly()应该更短,但是您需要区分连接错误和解析错误。

safe_fromJSON <- function(txt, encoding = "UTF-8") {

obj_lines <- readLines(con = txt, encoding = encoding)

check_json <- jsonlite::validate(txt = obj_lines)
if(check_json == TRUE ) {
obj_json <- fromJSON(txt = obj_lines)
} else {
obj_json <- fromJSON(txt = "[]") # "[]" represents an empty json.
}

obj_json
}
safe_fromJSON(txt = "https://www.predictit.org/api/Public/GetMarketChartData/99999?timespan=90d&maxContracts=9999&showHidden=true")
list()

最新更新