Skip to content

Instantly share code, notes, and snippets.

@apchamberlain
Created April 29, 2015 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apchamberlain/255f6400538037670835 to your computer and use it in GitHub Desktop.
Save apchamberlain/255f6400538037670835 to your computer and use it in GitHub Desktop.
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