R fromJSON无法打开连接

时间:2014-02-18 11:44:25

标签: json r web-services

我正在使用一个算法R,它调用一个Web服务来查询数据库并返回一个JSON对象。

url <- paste ('https://example.com?id=1'') 
document <- fromJSON (content = url, method = 'C') 

在我的机器上,当我运行到服务器并运行时,算法通常会运行不正常,我收到以下错误:

Error in file(con, "r") : cannot open the connection
Calls: fromJSON -> fromJSON -> I -> structure -> unique
Execution halted

网址有问题是https?

1 个答案:

答案 0 :(得分:2)

cannot open the connection之类的错误通常意味着文件不存在,或者您没有权限读取它。

你没有说你是使用rjson还是RJSONIO包,但是因为你包含了一个method参数,我猜它是前者。 rjson::fromJSON将其第一个参数视为JSON字符串。您应该使用file参数。

document <- fromJSON(file = url)

作为最佳实践,在从互联网解析内容时,您应该先下载它;然后解析它(分两个步骤)。这样,当出现错误并抛出错误时,您不会使用带宽重新加载它。

尝试将代码拆分为:

json_file <- "path/to/save/it/to/the_data.json"
download.file(url, json_file)
document <- fromJSON(file = json_file)

请注意,download.file默认情况下不支持https。在Windows下,您可以setInternet2()使用Internet Explorer的连接DLL,然后它可以正常工作。请参阅?download.file的详细信息部分。