Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send json response using plumber R

I need to send response from R using plumber package in below format

{
  "status": "SUCCESS",
  "code": "200",
  "output": {
    "studentid": "1001",
    "name": "Kevin"
  }
}

But I am getting below format

[
  "{\n  \"status\": \"SUCCESS\",\n  \"code\": \"200\",\n  \"output\": {\n    \"studentid\": \"1001\",\n    \"name\": \"Kevin\"\n  }\n}"
]

Please help me format this json properly

My Code

#* @post /sum
addTwo <- function(){
  library(jsonlite)
  x <- list(status = "SUCCESS", code = "200",output = list(studentid = "1001", name = "Kevin"))
  output<-toJSON(x,pretty = TRUE, auto_unbox = TRUE)
  return (output)
}
like image 629
Rajesh Kumar Duraisamy Avatar asked Mar 04 '17 06:03

Rajesh Kumar Duraisamy


People also ask

What is plumber API?

Plumber is an open-source R package that converts your existing R code into a web API; this enables you to leverage your R code from other platforms or programing languages. You could use Plumber to embed a graph created in R in a website, or to run a forecast on some data from a Java application.


2 Answers

I added an unboxedJSON serializer to the development version of plumber. Depending on when in the future this is being read, that serializer might have been published to CRAN and might even be the default serializer now (I'm still debating).

But for now, you can install the development version from GitHub (devtools::install_github("trestletech/plumber")) then add the @serializer unboxedJSON annotation to your function like so:

#* @post /sum
#* @serializer unboxedJSON
addTwo <- function(){
  list(status = "SUCCESS", code = "200",output = list(studentid = "1001", name = "Kevin"))

}

FYI if you ever do want to force plumber to return some text that you're providing directly, you should be able to set the $body element on res then return the res object from the function.

#* @get /
function(res){
  res$body <- "I am raw"
  res
}

which will return the unformatted, unserialized text I am raw in its response.

like image 127
Jeff Allen Avatar answered Oct 10 '22 06:10

Jeff Allen


Just remove the toJSON() wrapper. Plumber already does JSON serialisation so you are doing it twice by adding a toJSON function.

This should work.

 addTwo <- function(){
  x <- list(status = "SUCCESS", code = "200",output = list(studentid = "1001", name = "Kevin"))
  return (x)
}
like image 32
Lazarus Thurston Avatar answered Oct 10 '22 05:10

Lazarus Thurston