如何使用水管工R发送JSON响应 [英] How to send json response using plumber R
问题描述
我需要使用以下格式的水暖工包从R发送响应
I need to send response from R using plumber package in below format
{
"status": "SUCCESS",
"code": "200",
"output": {
"studentid": "1001",
"name": "Kevin"
}
}
但是我的格式不正确
[
"{\n \"status\": \"SUCCESS\",\n \"code\": \"200\",\n \"output\": {\n \"studentid\": \"1001\",\n \"name\": \"Kevin\"\n }\n}"
]
请帮助我正确设置此json格式
Please help me format this json properly
我的代码
#* @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)
}
推荐答案
我在水管工的开发版本中添加了unboxedJSON
序列化程序.取决于将来何时读取该序列化程序,该序列化程序可能已发布到CRAN,甚至现在可能是默认的序列化程序(我仍在辩论).
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).
但是,现在,您可以从GitHub(devtools::install_github("trestletech/plumber")
)安装开发版本,然后将@serializer unboxedJSON
批注添加到函数中,如下所示:
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"))
}
仅供参考,如果您确实要强制管道工返回直接提供的某些文本,则应该能够在res上设置$body
元素,然后从函数中返回res
对象.
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
}
,它将在响应中返回未格式化,未序列化的文本I am raw
.
which will return the unformatted, unserialized text I am raw
in its response.
这篇关于如何使用水管工R发送JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!