直接在 json 中创建 plumber.R return 字符串,而不是在只有一个元素的列表中
Make plumber.R return strings directly in json, not inside a list with one single element
当将字符串作为我的 plumber.R 响应的一部分时,它们总是封装在列表中,即使并且尤其是当它只是一个字符串而不是列表中的多个字符串时。
我知道这就是 R 通常处理字符串的方式,如下所示
> list(response = "This is my text")
$response
[1] "This is my text"
但我不确定如何在 Plumber 中操作输出以在我的 json 响应中获得所需的格式。
我的代码
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"
]
}
由于在 R 中一切都是向量,代码很难猜测什么应该变成单个值或 JSON 中的数组。当单个值存储在数组中时,称为 "boxing"。您可以通过更改用于端点的序列化程序来更改默认装箱行为。你可以做到
#* returns a fixed string
#* @serializer unboxedJSON
#* @get /mytext
get_mytext <- function(req, res) {
return(list(response = "This is my text"))
}
默认情况下 到 "unbox" 个长度为 1 的向量。
或者,您可以在回复中明确拆箱某些值
#* returns a fixed string
#* @get /mytext
get_mytext <- function(req, res) {
return(list(response = jsonlite::unbox("This is my text")))
}
当将字符串作为我的 plumber.R 响应的一部分时,它们总是封装在列表中,即使并且尤其是当它只是一个字符串而不是列表中的多个字符串时。
我知道这就是 R 通常处理字符串的方式,如下所示
> list(response = "This is my text")
$response
[1] "This is my text"
但我不确定如何在 Plumber 中操作输出以在我的 json 响应中获得所需的格式。
我的代码
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"
]
}
由于在 R 中一切都是向量,代码很难猜测什么应该变成单个值或 JSON 中的数组。当单个值存储在数组中时,称为 "boxing"。您可以通过更改用于端点的序列化程序来更改默认装箱行为。你可以做到
#* returns a fixed string
#* @serializer unboxedJSON
#* @get /mytext
get_mytext <- function(req, res) {
return(list(response = "This is my text"))
}
默认情况下 到 "unbox" 个长度为 1 的向量。
或者,您可以在回复中明确拆箱某些值
#* returns a fixed string
#* @get /mytext
get_mytext <- function(req, res) {
return(list(response = jsonlite::unbox("This is my text")))
}