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.
library("plumber")
#* returns a fixed string
#* @get /mytext
get_mytext <- function(req, res) {
return(list(response = "This is my text"))
}
{
"response": "This is my text"
}
{
"response": [
"This is my text"
]
}
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")))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With