Skip to content

Instantly share code, notes, and snippets.

@rabidaudio
Created December 18, 2015 22:10
Show Gist options
  • Save rabidaudio/40ea67495160faa46a21 to your computer and use it in GitHub Desktop.
Save rabidaudio/40ea67495160faa46a21 to your computer and use it in GitHub Desktop.
Convert JSON file to CSV
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