问题描述
我正在使用一种算法R,该算法R调用一个Web服务,该服务对数据库进行查询并返回JSON对象.
I am working with an algorithm R that calls a webservice that makes a query to a database and returns a JSON object.
url <- paste ('https://example.com?id=1'')
document <- fromJSON (content = url, method = 'C')
在我的机器上,当我进入服务器并运行时,该算法通常无法正常工作,出现以下错误:
On my machine the algorithm usually works bad when I go up to the server and run, I get the following error:
Error in file(con, "r") : cannot open the connection
Calls: fromJSON -> fromJSON -> I -> structure -> unique
Execution halted
URL是https会有问题吗?
There is some problem for the url be https?
推荐答案
诸如cannot open the connection
之类的错误通常表示该文件不存在,或者您没有读取该文件的特权.
Errors like cannot open the connection
often mean that the file doesn't exist, or you don't have privileges to read it.
您没有说使用的是rjson
还是RJSONIO
软件包,但是由于您包含了method
自变量,所以我猜它是前者. rjson::fromJSON
将其第一个参数视为JSON字符串.您应该改用file
参数.
You don't say whether you are using the rjson
or RJSONIO
package, but since you included a method
argument, I'm guessing that it's the former. rjson::fromJSON
treats its first argument as a string of JSON. You should be using the file
argument instead.
document <- fromJSON(file = url)
根据最佳做法,从Internet解析内容时,应先下载;然后解析它(分两个步骤).这样,当出现问题并引发错误时,您就不会用尽带宽重新下载它.
As a matter of best practice, when parsing content from the internet you should download it first; then parse it (in two separate steps). That way, when something goes wrong and an error is thrown, you don't use up bandwidth redownloading it.
尝试将您的代码拆分为:
Try splitting your code up into:
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
的详细信息"部分.
Note that download.file
doesn't support https
by default. Under Windows, you can do setInternet2()
to use Internet Explorer's connection DLL, and then it works. See the Details section of ?download.file
.
这篇关于R fromJSON无法打开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!