Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R plumber JSON serializer auto_unbox

Tags:

json

r

plumber

Following the example on the page http://plumber.trestletech.com/

I wrote myfile.R as

#* @post /test
test <- function(){
list(speech='aa',source='bb',displayText='cc')
}

And I ran the plumber code on it to convert int into an API

library(plumber)
r <- plumb("~/Work/myfile.R")
r$run(port=8000)

And Now when I perform an POST request on it using I get

curl -XPOST 'localhost:8000/test
-> {"speech":["aa"],"source":["bb"],"displayText":["cc"]}

But I want the square brackets to be removed. In simple toJSON calls it can be done using auto_unbox=TRUE but how can I do it in plumber. How can I write a custom serializer and use it in the above code?

like image 893
anonR Avatar asked Oct 28 '25 12:10

anonR


2 Answers

I figured the process to add custom serializers. Let's say we want to make a custom serializer for JSON and name it "custom_json" myfile.R would be

#* @serializer custom_json
#* @post /test
test <- function(){
list(speech='aa',source='bb',displayText='cc')
}

And while running plumber code it would go as

library(plumber)
library(jsonlite)

custom_json <- function(){
  function(val, req, res, errorHandler){
    tryCatch({
      json <- jsonlite::toJSON(val,auto_unbox=TRUE)

      res$setHeader("Content-Type", "application/json")
      res$body <- json

      return(res$toResponse())
    }, error=function(e){
      errorHandler(req, res, e)
    })
  }
}

addSerializer("custom_json",custom_json)
r <- plumb("~/Work/myfile.R")
r$run(port=8000)

And Now when I perform an POST request on it using I get

curl -XPOST 'localhost:8000/test
-> {"speech":"aa","source":"bb","displayText":"cc"}
like image 133
anonR Avatar answered Oct 30 '25 02:10

anonR


Plumber provides a number of serializers out of the box. unboxedJSON is one of them.

Simply use the @serializer unboxedJSON annotation on you endpoint.

You can also set the default serializer to be plumber::serializer_unboxed_json.

like image 41
theEricStone Avatar answered Oct 30 '25 01:10

theEricStone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!