Skip to content

Instantly share code, notes, and snippets.

@seanmorton
Created October 8, 2018 23:17
Show Gist options
  • Save seanmorton/ddb2c10a1e10c9150ff00238d9cb437c to your computer and use it in GitHub Desktop.
Save seanmorton/ddb2c10a1e10c9150ff00238d9cb437c to your computer and use it in GitHub Desktop.
CSV to JSON ruby script
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