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

和自甴很熟 提交于 2019-12-02 11:14:26

问题


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


回答1:


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

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

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


来源:https://stackoverflow.com/questions/51944328/sending-json-file-in-curl-and-receiving-it-in-r-using-plumber

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!