在 R 中导入 JSON 文件时忽略错误 [英] Ignore error when importing JSON files in R

查看:62
本文介绍了在 R 中导入 JSON 文件时忽略错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 for 循环,它从 solr 搜索服务器下载一个 json 文件.它循环包含关键字(在本例中为 100)的向量:

I have this for loop that download a json file from a solr search server. It loops over a vector that contain keywords (100, in this case):

library(jsonlite)
for (i in 1:100) {
  docs <- fromJSON(paste("http://myurl.com/solr/select?df=topic&fq=",keywords[i],"&indent=on&q=*:*&rows=1&wt=json",sep=""))
  numFound <- docs$response$numFound
  print(numFound)
}

它工作正常,直到遇到在 solr 上找不到的某个关键字,并返回此错误:

It works fine, until it reaches a certain keyword that is not found on the solr, and returns this error:

Error in open.connection(con, "rb") : HTTP error 400.

然后循环停止.

有没有办法忽略错误并继续循环?

Is there a way to ignore the error and proceed the loop?

我已经使用 tryCatch 阅读了一些东西,但仍然无法弄清楚.

I've read something using tryCatch but still couldn't figure it out.

推荐答案

tryCatch 更简单,您可以在关键字循环中使用函数 try.这将尝试加载 URL,但如果遇到错误将打印错误但继续下一个关键字.

Simpler than tryCatch, you can use the function try inside your keyword loop. This will attempt to load the URL, but if an error is encountered will print the error but continue to the next keyword.

library(jsonlite)
for (i in 1:100) {
  try({
    docs <- fromJSON(paste("http://myurl.com/solr/select?df=topic&fq=",keywords[i],"&indent=on&q=*:*&rows=1&wt=json",sep=""))
    numFound <- docs$response$numFound
    print(numFound)
  })
}

如果您也不想打印错误,请指定silent = TRUE:

If you also don't want to have the errors printed, specify silent = TRUE:

library(jsonlite)
for (i in 1:100) {
  try({
    docs <- fromJSON(paste("http://myurl.com/solr/select?df=topic&fq=",keywords[i],"&indent=on&q=*:*&rows=1&wt=json",sep=""))
    numFound <- docs$response$numFound
    print(numFound)
  }, silent = TRUE)
}

这篇关于在 R 中导入 JSON 文件时忽略错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆