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

qoefvg9y  于 8个月前  发布在  其他
关注(0)|答案(1)|浏览(85)

我正在努力创建一个嵌套/分层的JSON文件。实际上,我的文件将在不同的级别上有不同数量的孩子(从零到几个孩子),树中的每个“节点”都将具有相同的键:值对:name,id,type。记住这一点,我从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尝试了这个例子,但就我所能适应的来说,它不提供在终端节点以外的节点上添加键:值对的能力
任何帮助,让我到下一步将不胜感激。
谢谢!蒂姆

ny6fqffe

ny6fqffe1#

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

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

字符串

相关问题