Skip to content

Instantly share code, notes, and snippets.

@theFreedomBanana
Created November 8, 2015 09:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theFreedomBanana/47517c4c0d77fe1223a0 to your computer and use it in GitHub Desktop.
Save theFreedomBanana/47517c4c0d77fe1223a0 to your computer and use it in GitHub Desktop.
A ruby script to convert Json file to CSV
#Ruby version 2.1.1
require 'csv'
require 'json'
def json_to_csv(json_file, csv_file)
json_array = JSON.parse(File.open(json_file).read)
headers = collect_keys(json_array.first)
CSV.open(csv_file, "w", :write_headers=> true, :headers => headers) do |csv|
json_array.each { |item| csv << collect_values(item) }
end
end
def collect_keys(hash, prefix = nil)
arr = hash.map do |key, value|
if value.class != Hash
if prefix
"#{prefix}.#{key}"
else
key
end
else
if prefix
collect_keys(value, "#{prefix}.#{key}")
else
collect_keys(value, "#{key}")
end
end
end
arr.flatten
end
def collect_values(hash)
arr = hash.map do |key, value|
if value.class != Hash
if (value.class == Array)
value.join(',')
else
value
end
else
collect_values(value)
end
end
arr.flatten
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment