Skip to content

Instantly share code, notes, and snippets.

@sanxfxteam
Last active November 14, 2017 05:04
Show Gist options
  • Save sanxfxteam/7502426 to your computer and use it in GitHub Desktop.
Save sanxfxteam/7502426 to your computer and use it in GitHub Desktop.
R: flatten a JSON file into a data frame
## Example data.json
[{"event":"glop","params":{"name":"toto","value":"glop"}},
{"event":"glot","params":{"name":"toto","info":"gggg"}},
{"event":"gogo","params":"text"},
{"event":"gogo2"}
];
## Expected output
event params.name params.value params.info params
1 glop toto glop <NA> <NA>
2 glot toto <NA> gggg <NA>
3 gogo <NA> <NA> <NA> text
4 gogo2 <NA> <NA> <NA> <NA>
## Flattening function
dataframeFromJSON <- function(l) {
l1 <- lapply(l, function(x) {
x[sapply(x, is.null)] <- NA
unlist(x)
})
keys <- unique(unlist(lapply(l1, names)))
l2 <- lapply(l1, '[', keys)
l3 <- lapply(l2, setNames, keys)
res <- data.frame(do.call(rbind, l3))
return(res)
}
## Example
data <- fromJSON(paste(readLines('data.json'), collapse=""))
df <- dataframeFromJSON(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment