retrography
8/21/2015 - 6:07 AM

JSON to CSV convertor. Uses `jsonlite` R package, flattens all the hierarchical structure and converts all remaining lists/arrays into strin

JSON to CSV convertor. Uses jsonlite R package, flattens all the hierarchical structure and converts all remaining lists/arrays into strings.

#!/usr/bin/Rscript 

if (!require(jsonlite, quietly = TRUE, warn.conflicts = FALSE)) {
	stop("This program requires the `jsonlite` package. Please install it by running `install.packages('jsonlite')` in R and then try again.")
}

args <- commandArgs(trailingOnly = TRUE)

if (length(args) == 0) {
	input <- readLines(file("stdin"))
} else if (args[[1]] == "--help") {
	write("Usage: json2csv <json input file> <csv output file> \nAlternatively, you can redirect inputs and outputs using pipes, stdin and stdout.", 
		stderr())
	q()
} else {
	input <- readLines(args[[1]])
}

df <- fromJSON(input, flatten = TRUE)
listcols <- colnames(df[lapply(colnames(df), function(x) class(df[,x])) == "list"])
for (col in listcols) df[col] = data.frame(unlist(lapply(df[,col], function(x) toString(unlist(x)))))

if (length(args) > 1) {
	write.csv(df, args[[2]], row.names = FALSE)
} else {
	write.csv(df, stdout(), row.names = FALSE)
}