Method: CSV2JSON.parse

Defined in:
lib/csv2json.rb

.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