R - Parsing JSON code with multiple levels

Viewed 210

I'm trying to parse JSON using R. Using fromJSON() in the jsonlite package gets me most of the way there. But what's the most efficient way build out a data frame when the json has multiple levels?

Say I have this json code:

[
   {
      "id":"0001",
      "type":"donut",
      "batters":{
         "batter":[
            {
               "id":"1001",
               "type":"Regular"
            },
            {
               "id":"1002",
               "type":"Chocolate"
            },
            {
               "id":"1003",
               "type":"Blueberry"
            }
         ]
      }
   }
]

I read it in and parse using fromJSON

json <- readLines(...)
out <- fromJSON(json)

That gets me a data frame with 1 observation and 3 variables. The last variable is a list with all the "batter" values.

I want to build this out to get 3 observations with 4 variables.

id     type     batter.id     batter.type
0001   donut    1001          Regular
0001   donut    1002          Chocolate
0001   donut    1003          Blueberry

Can I do this with directly while parsing the json code? Or do I need to build out the table using something like unlist? (If so, how would this be done efficiently using something like unlist?)

1 Answers

With a bit more digging, I found unnest in tidyr.

unnest(out, batter, names_sep = ".")
Related