Opencpu简单函数json解析不起作用

时间:2015-06-02 19:19:48

标签: r opencpu jsonlite

您好我想为我的本地opencpu开发服务器提供一个简单的功能。

getLinearInterpolatedEstimateQuantil <- function(x, type, probs){
  result = quantile(data, type, probs)
  result #print for simpler debug
}

示例调试输入类似于

{"type":1,"x":[1,2,3,4,5,6,7,8,9,10],"probs":[0.05,0.25,0.75,0.95]}

但是有一个问题:当手动提供样本数据时:

debugInput = fromJSON(file("debugInput.json"))

代码编译。

但是当我尝试通过http访问它时:

opencpu$browse("library/myLibrary")
curl http://localhost:3469/ocpu/library/predictR/R/getLinearInterpolatedEstimateQuantil/Json -d '{"type":1,"x":[1,2,3,4,5,6,7,8,9,10],"probs":[0.05,0.25,0.75,0.95]}

' - H“Content-Type:application / json”

我只接收输出:

    unused arguments (type = 1, probs = probs)
In call:
getLinearInterpolatedEstimateQuantil(type = 1L, x = x, probs = probs)

所以我希望解析对数组有一些问题吗?

我希望你能告诉我我的代码有什么问题。

编辑:我了解到opencpu为我执行了json解析。但是代码仍然不起作用。 (https://www.opencpu.org/posts/scoring-engine/) 编辑:仍然无法正常工作 编辑: 奇怪: 调用本机函数有效:

curl http://localhost:5112/ocpu/library/stats/R/quantile/json -d '{"type":1,"x":[1,2,3,4,5,6,7,8,9,10],"probs":[0.05,0.25,0.75,0.95]}' -H "Content-Type: application/json"

但是调用我自己的函数会导致错误:

curl http://localhost:5112/ocpu/library/predictR/R/getLinearInterpolatedEstimateQuantil/json -d '{"type":1,"x":[1,2,3,4,5,6,7,8,9,10],"probs":[0.05,0.25,0.75,0.95]}' -H "Content-Type: application/json"
unused arguments (type = 1, probs = probs)
In call:
getLinearInterpolatedEstimateQuantil(type = 1L, x = x, probs = probs)

再次澄清我的功能:

getLinearInterpolatedEstimateQuantil <- function(x){
  result = quantile(data, type, probs)
  return (result)
}

再次编辑:

library(jsonlite)
myFunction <- function(x, type, probs){
result = quantile(x, type, probs)
return (result)
}

json <- '{"type":1,"x":[1,2,3,4,5,6,7,8,9,10],"probs":[0.05,0.25,0.75,0.95]}'
args <- fromJSON(json)
do.call(myFunction, args)

结果

100% 
10 

Warning message:
In if (na.rm) x <- x[!is.na(x)] else if (anyNA(x)) stop("missing values and NaN's not allowed if 'na.rm' is FALSE") :
  Bedingung hat Länge > 1 und nur das erste Element wird benutzt

并且

do.call(stats::quantile, args)

结果

5% 25% 75% 95% 
  1   3   8  10 

为什么第一次调用会产生不同输出的警告? 为什么第二次通话有效?

1 个答案:

答案 0 :(得分:1)

对于-H "Content-Type: application/json"的RCP,JSON对象中的顶级名称必须与函数的参数名称匹配。您可以按如下方式测试:

library(jsonlite)
json <- '{"type":1,"data":[1,2,3,4,5,6,7,8,9,10],"quantil":[0.05,0.25,0.75,0.95]}'
args <- fromJSON(json)
result <- do.call(getLinearInterpolatedEstimateQuantil, args)

因此,假设您希望坚持使用JSON有效负载,那么您的函数应如下所示:

getLinearInterpolatedEstimateQuantil <- function(data, quantil, type = 1){

}

例如直接调用quantile函数:

curl http://public.opencpu.org/ocpu/library/stats/R/quantile/json -d \
'{"type":1,"x":[1,2,3,4,5,6,7,8,9,10],"probs":[0.05,0.25,0.75,0.95]}' \
-H "Content-Type: application/json"

请注意,json blob type probsx的参数与分位数的参数名称匹配。