-
-
Save janetlee/591918b4c4814c710cb99ed1aad6485c 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>
This file contains 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
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