Created
June 27, 2016 14:28
-
-
Save karthik/d5285c4ececfbd4a365ce628f3244f6a to your computer and use it in GitHub Desktop.
flatten_json.R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # This example shows you how to turn a JSON (and nested JSON) | |
| # response into a data.frame for further use in a R package | |
| sample_response <- '{ | |
| "crust": "original", | |
| "toppings": ["cheese", "potatoes", "garlic"], | |
| "status": "cooking", | |
| "customer": { | |
| "name": "Garrett", | |
| "phone": "573-111-1111" | |
| } | |
| }' | |
| library(jsonlite) | |
| # Convert data from JSON to a list | |
| raw_data <- fromJSON(sample_response, flatten = TRUE) | |
| # Then unlist the list | |
| raw_data_csv <- unlist(raw_data) | |
| # Transpose it since we need from long to wide | |
| raw_data_csv <- t(raw_data_csv) | |
| # Now turn it into a data.frame | |
| # Be sure to set stringsAsFactors = FALSE to avoid problems in the future | |
| raw_data_csv <- data.frame(raw_data_csv, stringsAsFactors = FALSE) | |
| View(raw_data_csv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment