Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create nested/hierarchical JSON with R and JSONLITE?

Tags:

json

r

jsonlite

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

like image 808
Tim Avatar asked Apr 05 '17 23:04

Tim


1 Answers

You can create dataframe first and then assign the frame as a list into cell.

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")
like image 68
Hej Ja Avatar answered Oct 05 '22 07:10

Hej Ja