Skip to content

Instantly share code, notes, and snippets.

@retrography
Last active February 26, 2021 23:09
Show Gist options
  • Select an option

  • Save retrography/fa622bb57d1ca25ecef8 to your computer and use it in GitHub Desktop.

Select an option

Save retrography/fa622bb57d1ca25ecef8 to your computer and use it in GitHub Desktop.

Revisions

  1. retrography revised this gist Aug 21, 2015. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion json2csv.R
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    #!/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.")
    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)
  2. retrography created this gist Aug 21, 2015.
    27 changes: 27 additions & 0 deletions json2csv.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    #!/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)
    }