Created
December 18, 2015 22:10
-
-
Save rabidaudio/40ea67495160faa46a21 to your computer and use it in GitHub Desktop.
Convert JSON file to CSV
This file contains hidden or 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' | |
# parse some json into hash array | |
data = JSON.parse(File.read("in.json")) | |
# get all headers appearing anywhere in data | |
keys = [] | |
data.each do |hash| | |
keys = keys.concat(hash.keys).uniq | |
end | |
f = File.open "out.csv", "w" | |
f << CSV.generate do |csv| | |
csv << keys # write headers | |
data.each do |hash| | |
# make a new hash, which sets any missing key values to nil | |
h2 = {} | |
keys.each do |k| | |
h2[k] = hash[k] | |
end | |
csv << h2.values # write those values to csv | |
end | |
end | |
f.close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment