Created
April 29, 2015 22:35
-
-
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.
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 | |
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