Created
May 24, 2012 17:41
-
-
Save christiangenco/2783011 to your computer and use it in GitHub Desktop.
Translate .csv files to .json objects using the first line of the csv file as a list of keys
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
# csv_to_json.rb | |
# a simple utility to translate csv files to json objects | |
# using the first line of the csv file as a list of keys | |
# The keys in the first line of the csv file are downcased and | |
# underscored (ex: "First Name" => "first_name") | |
# Example usage: | |
# csv_to_json.rb my_csv_file.csv | |
# => outputs JSON interpretation of my_csv_file.csv to STDOUT | |
# csv_to_json.rb *.csv | |
# => translates each .csv file to a .json file and writes | |
# these files to disk | |
# Example translation: | |
# =test.csv | |
# First Name, Last Name, Email | |
# John, Doe, [email protected] | |
# Jane, Doe, [email protected] | |
# | |
# $ ruby csv_to_json.rb test.csv > test.json | |
# or | |
# $ csv_to_json *.csv | |
# | |
# =test.json | |
# [{"first_name":"John","last_name":" Doe","email":" [email protected]"},{"first_name":"Jane","last_name":" Doe","email":" [email protected]"}] | |
def parse_csv(filename) | |
require 'csv' | |
keys = nil | |
data = [] | |
CSV.foreach(filename) do |row| | |
# set keys as the first row | |
if keys.nil? | |
keys = row.map{|k| k.downcase.strip.gsub(" ", '_')} | |
next | |
end | |
item = {} | |
row.each_with_index{|e, i| | |
item[keys[i]] = e | |
} | |
data << item | |
end | |
data | |
end | |
def csv_to_json(filename) | |
require 'json' | |
parse_csv(filename).to_json | |
end | |
# ===main=== | |
if ARGV.size == 1 | |
# print a single file to STDOUT | |
puts csv_to_json(ARGV[0]) | |
elsif ARGV.size > 1 | |
# we recieved a block of filenames | |
# translate each one and write it to disk | |
ARGV.each do |filename| | |
print "Processing \"#{filename}\" => " | |
output_filename = filename.sub(/\.csv$/, ".json") | |
File.open(output_filename, 'w'){|f| | |
f.puts csv_to_json(filename) | |
} | |
puts "\"#{output_filename}\"" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment