I am struggling to create a nested/hierarchical JSON file. In reality, my file will have varying numbers of children at different levels (from zero children to several), and each "node" in the tree will have the same key:value pairs: name, id, type. Bearing that in mind, my output from R to JSON should appear similar to:
{"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"}
]}
]}
I've tried creating JSON from lists. I know I need a dataframe somewhere in here, but I can't see how to do this.
This code gets me close:
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)
Resulting in this output:
{
"name": "I",
"id": "001",
"type": "roman",
"children": {
"name": "1",
"id": "002",
"type": "arabic",
"children": {
"name": "A",
"id": "003",
"type": "alpha-U"
}
}
}
The children are not formed properly and I don't see how to get multiple children per level.
I tried this example from SO: How to write to json with children from R but as far as I have been able adapt it, it does not provide the ability to add the key:value pairs at nodes other than the terminal node
Any help to get me to the next steps would be greatly appreciated.
Thanks! Tim
mylist <- list( name="I", id="001", type="roman", children=list( list( name="1", id="002", type="arabic" ), list( name="A", id="003", type="alpha-U" ) ) )
? I think you just wantchildren
to be a list of lists. – thelatemail