4

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

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

4

1 回答 1

6

plumber如果您通过以下方式发送 JSON,则透明地解包 JSON --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 我得到:

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

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" ] }
]
于 2018-08-21T09:10:56.440 回答