Create nested / hierarchical JSON with R and JSONLITE?

I am trying to create a nested / hierarchical JSON file. In fact, my file will have a different number of children at different levels (from zero to several), and each "node" in the tree will have the same pairs: value: name, id, type. With that in mind, my output from R to JSON should look something like this:

{"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 tried to create JSON from lists. I know I need an info frame around here somewhere, but I can't see how.

This code is closing me:

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)

      

Resultant result:

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

      

The kids are not formed correctly and I don't see how to get multiple kids per level.

I tried this example from SO: How to write json with children from R but as far as I could adapt it, it does not provide the ability to add key: value pairs in non-terminal nodes

Any help is welcome to help me with the next steps.

Thank! Tim

+3


source to share





All Articles