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