r - 解析错误:打开错误 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
成为一个空白字符串,或者在打开 URLFALSE
时fromJSON()
遇到错误。
解决方案
这是我通常的做法,如果(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()
推荐阅读
- c# - 我想使用 C# 代码恢复 SQL Server 数据库
- powershell - Powershell 添加 reg 密钥
- python - 从 SQL 语法到 SQLAlchemy 语法
- c# - 直接引用 Razor 类库程序集
- c# - C# - 在另一个方法中实现抽象或接口方法
- docker - Dockerfile 错误:standard_init_linux.go:207:exec 用户进程导致“没有这样的文件或目录
- ruby-on-rails - 找不到 redis_cache_store 的缓存存储适配器(无法加载此类文件 -- active_support/cache/redis_cache_store)
- xaml - 如何让我的 Xamarin xaml 设计器工作?
- python - 从不同的进程对接 PyQt Windows
- ios - iOS:应用启动后,UIApplication.sharedApplication.keyWindow.rootViewController==nil