Sha256: 3b99b07e4862b4c32fe03914cb7093406478f73a642c1b3dea3d57cc251dc62c

Contents?: true

Size: 998 Bytes

Versions: 1

Compression:

Stored size: 998 Bytes

Contents

require 'fastercsv'
require 'json'

module CSV2JSON
    VERSION = "0.1.0"
    
    # convert an input string value to integer or float if applicable
    def convert(val)
        return Integer(val) if val.to_i.to_s == val
        Float(val) rescue val
    end

    # input and output are file objects, you can use StringIO if you want to work in memory
    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
    
    module_function :parse
    module_function :convert
    
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
csv2json-0.1.0 lib/csv2json.rb