gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:45:19 28 4
gpt4 key购买 nike

我正在努力创建嵌套/分层 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"
}
}
}

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

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

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

谢谢!
蒂姆

最佳答案

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

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

关于json - 使用 R 和 JSONLITE 创建嵌套/分层 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43243320/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com