首页 > 解决方案 > 解析错误:打开错误 URL 时 fromJSON() 中的过早 EOF

问题描述

这个声明给了我一个错误。

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 脚本可以处理它而不会崩溃?相反,我想somevar成为一个空白字符串,或者在打开 URLFALSEfromJSON()遇到错误。

标签: r

解决方案


这是我通常的做法,如果(a)没有与服务器或文件的连接,但(b1)安全地获得一个空的json(即list())如果有一个文件的连接,则它会失败,但事实证明一个不可读/格式错误的 json。实现 purrr's safely()or应该更短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()

推荐阅读