我正在尝试构建一个循环函数,从R中的API中捕获json,如下所示:
for(j in 1:700){
tx_i <- paste0("https://example.com/api/",bloco_i_final$tx[j])
txi <- GET(tx_i, add_headers(Authorization = full_token, Accept =
header_type), timeout(120), verbose())
conteudo <- content(txi, type = 'text', encoding = "UTF-8")
tx_i_final <- rjson::fromJSON(getURL(tx_i))
(some functions that bind this data.frames)
}
但有时,在循环中,此函数最终会显示错误消息:
Error in fromJSON(conteudo) : unexpected character 'B'
我想构建一个识别此错误的while函数并重复该过程。
示例:
for(j in 1:700){
#THIS PART
while(identifies erro in FROMJSON){
tx_i <- paste0("https://example.com/api/tx/",bloco_i_final$tx[j])
txi <- GET(tx_i, add_headers(Authorization = full_token, Accept =
header_type), timeout(120), verbose())
conteudo <- content(txi, type = 'text', encoding = "UTF-8")
tx_i_final <- rjson::fromJSON(getURL(tx_i))
} #REPEATS ALL PROCESS WHILE ERRO EXISTS
(some functions that bind this data.frames)
}
答案 0 :(得分:1)
您可以使用的一个技巧是在循环中实现tryCatch(.)
方法,然后减少计数器。例如:
for(j in 1:100){
tryCatch({
#Define the link with all positions
### Implement your method here!! ###
}, error = function(err) {
#Print the error:
print(paste("MY_ERROR: ",err))
#Decrease your counter to try again
j<- (j-1)
#Wait some time before try again...
Sys.sleep(10)
})
}