使用管道工在 curl 中发送 json 文件并在 R 中接收它

Sending json file in curl and receiving it in R using plumber

我需要发送一个包含多个值的 json 文件并使用水管工在 R 中接收它,我试过这个但它似乎不起作用,

library("rjson")
#install.packages("rjson")
#* @get /predict
#* @post /predict
function(predict) {
  # Load the package required to read JSON files.
  library("rjson")
  # Give the input file name to the function.
  result <- fromJSON(file = "input_v3.json")
  print(result)
  result <- as.data.frame(result)
  write.table(result, file="testing_v3_xyz.csv", sep=",", row.names=FALSE, col.names=TRUE, append = T)
}


The curl command i used is curl -F data=@input_v3.json http://xx.xxx.xxx.xx:8000/predict

我需要在桌面 运行 在 aws

中发送一个 IP 地址为 Rstudio

plumber 如果您通过 --data:

发送 JSON 透明地解压 JSON
library(plumber)

#* parse JSON
#* @param a  a vector
#* @param b  a vector
#* @get /predict
#* @post /predict
function(a, b) {
  result <- data.frame(a = as.numeric(a), b = as.numeric(b))
  write.table(result, file="testing_v3_xyz.csv", sep=",",
              row.names=FALSE, col.names=TRUE, append = T)
}

运行 这个 API 在本地我得到:

$ cat foo.json 
{ "a":["1","2","3","4","5","6","7","8" ], "b":["1","2","3","4","5","6","7","8" ] }
$ curl --data @foo.json  http://localhost:8414/predict
{}
$ cat ~/learning/Whosebug/testing_v3_xyz.csv 
"a","b"
1,1
2,2
3,3
4,4
5,5
6,6
7,7
8,8

如果 JSON 的顶层是数组而不是对象,则不能使用命名参数将数据获取到函数中。但是,您可以使用 req$postBody 访问发布的内容:

library(plumber)

#* parse JSON
#* @param req  the request object
#* @get /predict
#* @post /predict
function(req) {
  result <- as.data.frame(lapply(jsonlite::fromJSON(req$postBody), unlist))
  write.table(result, file="testing_v3_xyz.csv", sep=",", row.names=FALSE, col.names=TRUE, append = T)
}

对我来说,这适用于这样的示例数据:

[
  { "a":["1","2","3","4","5","6","7","8" ],
    "b":["1","2","3","4","5","6","7","8" ] },
  { "a":["1","2","3","4","5","6","7","8" ], 
    "b":["1","2","3","4","5","6","7","8" ] }
]