Skip to content

Instantly share code, notes, and snippets.

@chreke
Last active December 26, 2015 04:49
Show Gist options
  • Save chreke/7096702 to your computer and use it in GitHub Desktop.
Save chreke/7096702 to your computer and use it in GitHub Desktop.
Convert JSON to CSV using Ruby
#!/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