Last active
December 26, 2015 04:49
-
-
Save chreke/7096702 to your computer and use it in GitHub Desktop.
Convert JSON to CSV using Ruby
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
#!/usr/bin/env ruby | |
# USAGE: | |
# | |
# json-to-csv [filename] | |
# | |
# This script takes a JSON array of objects as its input and outputs | |
# the data as CSV to STDOUT. The JSON array can be fed to the | |
# script either via STDIN or by supplying a filename as an argument. | |
require 'csv' | |
require 'json' | |
data = JSON.parse ARGF.read | |
headers = data.reduce([]) {|memo, x| (memo + x.keys).uniq } | |
csvstring = CSV.generate do |csv| | |
csv << headers | |
data.each {|x| csv << x.values_at(*headers) } | |
end | |
puts csvstring |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment