Last active
April 25, 2018 13:15
-
-
Save sapslaj/091cd7b2827fcacce9e371c302cd07d4 to your computer and use it in GitHub Desktop.
Convert JSON to CSV and vice-vera
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' | |
require 'active_support/all' | |
def json_to_csv(json_file, csv_file) | |
CSV.open(csv_file, "w") do |csv| | |
data = JSON.parse(File.read(json_file)) | |
csv << data.inject([]) { |keys, d| [keys, d.keys].flatten.uniq }.map(&:titleize) | |
data.each { |d| csv << d.keys.map { |key| d[key] } } | |
end | |
end | |
def csv_to_json(csv_file, json_file) | |
data = [] | |
headers = [] | |
CSV.foreach(csv_file) do |row| | |
if headers.empty? | |
headers = row.map(&:underscore) | |
else | |
data.push(row.map.with_index { |value, index| [headers[index], value] }.to_h) | |
end | |
end | |
File.open(json_file, 'w') { |f| f.write JSON.pretty_generate(data) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment