Category Archives: script

Ruby utility script – csv2json

A script that I wrote and am using more and more.

Arguments are “filename.ext”

#!/usr/bin/ruby
require ‘json’

source = ARGV[0]
if source.nil?
puts “Missing filename argument”
puts “USAGE: #{$0} filename.ext”
exit(1)
end

unless source && FileTest.exists?(source)
puts “#{source} not found!”
exit(1)
end

puts “Processing ‘#{source}'”

SEPARATOR_COMMA = /,/
SEPERATOR_PIPE = /|/
SEPERATOR_TAB = /\t/

file = File.new(source,’r’)
ext = File.extname(source).to_s.downcase

outname = source.sub(ext,’.json’)
out = File.new(outname,’w’)

sep = case ext
when ‘.csv’
SEPARATOR_COMMA
when ‘.psv’
SEPARATOR_PIPE
when ‘.tab’
SEPARATOR_TAB
else
# assume comma since it is *CSV*2json
SEPARATOR_COMMA
end
puts “Extension: #{ext} using ‘#{sep.source}'”

lines = file.read.split(/\n\r?/)
file.close

header = lines[0].split(sep)
data = lines.drop(1).map {|item| item.split(sep)}

outdata = []

data.each do |item|
h = Hash.new()
for i in (0..(header.size – 1))
h[header[i]] = item[i]
end
outdata << h end out.write outdata.to_json out.close puts "File written to " + out.path