Skip to content

Instantly share code, notes, and snippets.

@dharamgollapudi
Forked from jordan-thoms/convertjsoncsv.rb
Created July 19, 2018 19:44
Show Gist options
  • Save dharamgollapudi/cdfb400d38a14924236a0169e909cdd9 to your computer and use it in GitHub Desktop.
Save dharamgollapudi/cdfb400d38a14924236a0169e909cdd9 to your computer and use it in GitHub Desktop.
Code to convert json to csv, with correct headings Usage: ruby convertjsoncsv.rb <input file> <output file>
require 'csv'
require 'json'
require "set"
json = JSON.parse(File.open(ARGV[0]).read)["results"]
# Pass 1: Collect headings
headings = SortedSet.new
json.each do |hash|
headings.merge(hash.keys)
end
# Pass 2: Fill data into the headings
csv_string = CSV.open(ARGV[1], "wb") do |csv|
csv << headings
json.each do |hash|
row = {}
headings.each do |heading|
row[heading] = nil
end
hash.each do |k,v|
row[k] = v.to_s.gsub(/\r\n?/, "").delete("\n").delete("\r")
end
csv << row.values
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment