Module: CSV2JSON

Defined in:
lib/csv2json.rb,
lib/csv2json-version.rb

Constant Summary collapse

VERSION =
"0.1.1"

Class Method Summary collapse

Class Method Details

.convert(val) ⇒ Object

convert an input string value to integer or float if applicable



8
9
10
11
# File 'lib/csv2json.rb', line 8

def convert(val)
    return Integer(val) if val.to_i.to_s == val
    Float(val) rescue val
end

.parse(input, output, headers = nil) ⇒ Object

input and output are file objects, you can use StringIO if you want to work in memory



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/csv2json.rb', line 14

def parse(input, output, headers=nil)
    result = Array.new

    FasterCSV.new(input).each do |row|
        # treat first row as headers if the caller didn't provide them
        unless headers 
            headers = row
            next
        end
        
        # build JSON snippet and append it to the result
        snippet = Hash.new
        headers.each_index { |i| snippet[headers[i]] = self.convert(row[i]) }
        result << snippet
    end
    
    output << JSON.pretty_generate(result)
end