R 水管工,如何创建嵌套 JSON

R Plumber, How to create nested JSON

需要帮助,我刚用 R Plumber 创建 API,我只是希望结果 Json 是这样的

而不是像这样

下面是我的 R Plumber 脚本

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
  
}

非常感谢任何类型的建议

更新

@deschen 的替代解决方案正好解决了这个问题,我创建 Web 应用程序的队友可以使用这个解决方案。

替代解决方案如下:

  {
  "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"
    }
  ]
} 
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

给出:

{
  "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"
    }
  ]
}