Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple CSV-to-JSON with no external dependencies other than the default OS X Ruby install. Because I keep forgetting how to do this. Pipe through `jq` for prettier output.
#!/usr/bin/env ruby
require 'json'
# Beware, this doesn't support embedded escaped commas, but it does
# handle quotes around field values with spaces in them correctly.
class Array
def to_h()
# [[a, 1], [b, 2]...] => {'a'=>1, 'b'=>2, ...}
rval = {}
for e in self do
rval[e[0]] = e[1]
end
return rval
end
end
def zapquotes(s)
s = s.match(/^['"]*(.*)['"]*$/)[0]
return s
end
line = gets
headings = line.rstrip.split(/,/)
arr = []
while (1) do
line = gets
if (!line) then
break
end
rec = line.rstrip.split(/,/)
rec = rec.map {|e| zapquotes(e) }
arr.push(headings.zip(rec).to_h)
end
puts arr.to_json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.