使用 R 和 JSONLITE 创建嵌套/分层 JSON?

Tim*_*Tim 6 json r jsonlite

我正在努力创建嵌套/分层 JSON 文件。实际上,我的文件将在不同级别(从零个子节点到多个子节点)具有不同数量的子节点,并且树中的每个“节点”将具有相同的键:值对:名称、ID、类型。记住这一点,我从 R 到 JSON 的输出应该类似于:

{"name": "I",
 "id": "001",
 "type": "roman",
 "children": [
     {"name": "1",
      "id": "002",
      "type": "arabic", 
      "children": [
          {"name": "A", 
           "id": "003",
           "type": "alpha-U"},
          {"name": "B", 
           "id": "004",
           "type": "alpha-U"}
       ]},
     {"name": "2",
      "id": "005",
      "type": "arabic", 
      "children": [
          {"name": "C", 
           "id": "005",
           "type": "alpha-U"},
          {"name": "D", 
           "id": "006",
           "type": "alpha-U"}
       ]}
]}  
Run Code Online (Sandbox Code Playgroud)

我试过从列表中创建 JSON。我知道我在这里的某个地方需要一个数据框,但我不知道如何做到这一点。

这段代码让我接近:

mylist <- list(name="I", id="001", type="roman",
               children=list(name="1", id="002", type="arabic",
                      children=list(name="A", id="003", type="alpha-U")
               ))
jsonlite::toJSON(mylist, pretty=TRUE, auto_unbox=TRUE)
Run Code Online (Sandbox Code Playgroud)

导致此输出:

{
  "name": "I",
  "id": "001",
  "type": "roman",
  "children": {
    "name": "1",
    "id": "002",
    "type": "arabic",
    "children": {
      "name": "A",
      "id": "003",
      "type": "alpha-U"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

孩子没有正确形成,我不知道如何在每个级别获得多个孩子。

我从 SO 中尝试了这个示例: How to write to json with children from R 但就我已经能够适应它而言,它不提供在终端节点以外的节点上添加键:值对的能力

任何帮助我进行下一步的帮助将不胜感激。

谢谢!蒂姆

小智 4

您可以先创建数据框,然后将框架作为列表分配到单元格中,如下所示:

hierarchy1 <- data.frame( name = c("I")
                          , id = c("001")
                          , type = c("roman"))

level1 <- data.frame(name = c("1", "2")
                     , id = c("002", "005")
                     , type = c("arabic", "arabic"))

level2 <- data.frame(name = c("A", "B")
                      , id = c("003","004")
                      , type = c("arabic","arabic"))


level1[1, "children"][[1]] <-   list(level2)
level1[2, "children"][[1]] <-   list(level2)
hierarchy1[1, "children"][[1]] <- list(level1)

write_json(hierarchy1, "yourJson.json")
Run Code Online (Sandbox Code Playgroud)