问题
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