Created
January 10, 2009 17:56
-
-
Save subtleGradient/45513 to your computer and use it in GitHub Desktop.
convert CSV to JSON hash of hashes
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 | |
| # convert CSV to JSON hash of hashes | |
| # uses the first column as the ID column, must be unique per row | |
| # takes the CSV filepath as first argument | |
| # fallsback to STDIN when there are no arguments | |
| require 'rubygems' | |
| require 'csv' | |
| require 'json' | |
| csv_filepath = ARGV[0] | |
| csv_data = CSV.read(csv_filepath) if csv_filepath | |
| csv_data = CSV.parse(STDIN.read) unless csv_data | |
| abort("No data to parse :'(") unless csv_data | |
| headers = csv_data.shift.map {|i| i.to_s } | |
| string_data = csv_data.map {|row| row.map {|cell| cell.to_s } } | |
| array_of_hashes = string_data.map {|row| Hash[*headers.zip(row).flatten] } | |
| # print array_of_hashes.to_json | |
| hash_of_hashes = {} | |
| array_of_hashes.each do |data| | |
| hash_of_hashes[ data[headers.first] ] = data | |
| end | |
| print hash_of_hashes.to_json |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment