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

问题描述:

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

I need to send a json file with multiple values and receive it in R using plumber, ive tried this but it doesnt seem to work,

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

我需要向其发送一个IP地址,该IP地址是在AWS上运行的Desktop中的Rstudio.

I need to send it a an ip address that is Rstudio in Desktop running on aws

plumber如果通过--data发送JSON,则透明地解压缩JSON:

plumber unpacks JSON transparently if you send it in via --data:

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:

Running this API locally I get:

$ 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/stackoverflow/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来访问发布的内容:

If the top level of the JSON is an array as opposed to an object, you cannot use named parameters to get the data into the function. However, you can use req$postBody to access the posted content:

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)
}

对我来说,它适用于以下示例数据:

For me this works for sample data like this:

[
  { "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" ] }
]