Created
October 8, 2018 23:17
-
-
Save seanmorton/ddb2c10a1e10c9150ff00238d9cb437c to your computer and use it in GitHub Desktop.
CSV to JSON ruby script
This file contains 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 'json' | |
require 'csv' | |
def csv_to_json(csv) | |
object = {} | |
CSV.parse(csv, headers: true) do |row| | |
compound_key = row[0] | |
val = row[1] | |
key_parts = compound_key.split('.') | |
add_key(object, key_parts, val) | |
end | |
JSON.pretty_generate(object) | |
end | |
def add_key(hash, key_parts, val) | |
key_part = key_parts.shift | |
if key_parts.count.zero? | |
hash[key_part] = val | |
return hash | |
end | |
hash[key_part] ||= {} | |
hash[key_part] = add_key(hash[key_part], key_parts, val) | |
hash | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment