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

时间:2017-04-05 23:38:03

标签: 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"}
       ]}
]}  

我尝试过从列表中创建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)

导致此输出:

{
  "name": "I",
  "id": "001",
  "type": "roman",
  "children": {
    "name": "1",
    "id": "002",
    "type": "arabic",
    "children": {
      "name": "A",
      "id": "003",
      "type": "alpha-U"
    }
  }
}

孩子们形成不正确,我不知道每个级别如何生育多个孩子。

我从SO尝试了这个例子: How to write to json with children from R 但据我所知,它不能提供在终端节点以外的节点上添加密钥:值对的能力

非常感谢帮助我完成下一步的任何帮助。

谢谢! 添

1 个答案:

答案 0 :(得分:2)

您可以先创建数据框,然后将其作为列表分配到单元格中。

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")