Created
November 8, 2015 09:57
-
-
Save theFreedomBanana/47517c4c0d77fe1223a0 to your computer and use it in GitHub Desktop.
A ruby script to 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
#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