Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make plumber.R return strings directly in json, not inside a list with one single element

Tags:

rest

r

plumber

When having strings as part of my plumber.R responses, they are always encapsulated in lists, even and especially when it's only a single string and not multiple strings in a list.

I'm aware this this is how R generally seems to handle strings, as follows

>  list(response = "This is my text")
$response
[1] "This is my text"

but I'm unsure how to manipulate the output in Plumber to get the desired format in my json response.

My code

library("plumber")

#* returns a fixed string
#* @get /mytext
get_mytext <- function(req, res) {
  return(list(response = "This is my text"))
}

Expected output

{
  "response": "This is my text"
}

Actual output

{
  "response": [
    "This is my text"
  ]
}
like image 643
quassy Avatar asked Oct 25 '25 19:10

quassy


1 Answers

Since everything is a vector in R, it's not easy for code to guess what should be turned into a single value or an array in JSON from. When a single value is stored in an array, that's referred to as "boxing". You can change the default boxing behavior by changing the serializer used for your end point. You can do

#* returns a fixed string
#* @serializer unboxedJSON
#* @get /mytext
get_mytext <- function(req, res) {
  return(list(response = "This is my text"))
}

to "unbox" vectors of length 1 by default.

Alternatively you can explicitly unbox certain values in your response

#* returns a fixed string
#* @get /mytext
get_mytext <- function(req, res) {
  return(list(response = jsonlite::unbox("This is my text")))
}
like image 132
MrFlick Avatar answered Oct 28 '25 09:10

MrFlick