Skip to content

Instantly share code, notes, and snippets.

@karthik
Created June 27, 2016 14:28
Show Gist options
  • Select an option

  • Save karthik/d5285c4ececfbd4a365ce628f3244f6a to your computer and use it in GitHub Desktop.

Select an option

Save karthik/d5285c4ececfbd4a365ce628f3244f6a to your computer and use it in GitHub Desktop.
flatten_json.R
# 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