3

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
  • 1
    You've already sorted it more cleanly, but you could use unlist in a slightly more roundabout way - data.frame(lapply(fromJSON(txt, flatten=TRUE), unlist, rec=FALSE)) for instance. Commented Aug 4, 2020 at 3:39

1 Answer 1

2

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

unnest(out, batter, names_sep = ".")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.