Reputation: 83
Need Help, I just create API with R Plumber, I just would like the Result Json will be like this
Instead of like this
below are my R Plumber script
library(plumber)
library(jsonlite)
#* @get /nested_json
#* @serializer unboxedJSON
function() {
main_info <- data.frame(
Name = "John",
Address = "Stret No. 1",
Point = "600"
)
reason_info <- data.frame(code = c('AAA', 'BBB', 'CCC', NA, 'EEE'),
descriptiom = c('low value of point A', 'low value of point B', 'low value of point C', NA, 'low value of point D') )
main_info[1, "reason"][[1]] <- list(reason_info)
final_output <- as.list(main_info)
final_output
}
Thanks a lot for any kind of suggestion
UPDATE
The alternative solution from @deschen just solve the problem, my teammates that created the Web Application could use this solution.
the alternative solution are like below :
{
"Name": "John",
"Address": "Stret No. 1",
"Point": "600",
"reason": [
{
"code": "AAA",
"description": "low value of point A"
},
{
"code": "BBB",
"description": "low value of point B"
},
{
"code": "CCC",
"description": "low value of point C"
},
{
"code": null,
"description": null
},
{
"code": "EEE",
"description": "low value of point D"
}
]
}
Upvotes: 1
Views: 256
Reputation: 10996
library(tidyverse)
library(jsonlite)
reason_info <- data.frame(code = c('AAA', 'BBB', 'CCC', NA, 'EEE'),
description = c('low value of point A',
'low value of point B',
'low value of point C',
NA,
'low value of point D'))
reason_info_new <- reason_info %>%
mutate(new = apply(across(everything()), 1, as.list)) %>%
pull(new)
full <- list(Name = "John",
Address = "Stret No. 1",
Point = "600",
reason = reason_info_new)
myJSON <- toJSON(full, pretty = TRUE, auto_unbox = TRUE)
myJSON
which gives:
{
"Name": "John",
"Address": "Stret No. 1",
"Point": "600",
"reason": [
{
"code": "AAA",
"description": "low value of point A"
},
{
"code": "BBB",
"description": "low value of point B"
},
{
"code": "CCC",
"description": "low value of point C"
},
{
"code": null,
"description": null
},
{
"code": "EEE",
"description": "low value of point D"
}
]
}
Upvotes: 1