Sha256: 89df3c1d87eadb0733d8cf2a29685efbd278eb13c1e523d5f1b686b75131d818

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 KB

Contents

require 'rubygems'
require 'csv'
require 'json'
require 'orderedhash'
require File.join(File.expand_path(File.dirname(__FILE__)), '..', 'lib', 'csv2json-version.rb')

module CSV2JSON

    # 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, csvOptions={}, gemOptions={})
        result = Array.new

        CSV.new(input, csvOptions).each do |row|
            # treat first row as headers if the caller didn't provide them
            unless headers 
                headers = row
                next
            end

            if gemOptions[:skipFirstRow] then
                gemOptions[:skipFirstRow] = false
                next
            end
            
            # build JSON snippet and append it to the result
            snippet = OrderedHash.new
            headers.each_index { |i| snippet[headers[i]] = self.convert(row[i]) }
            result << snippet
        end
        
        if gemOptions[:pretty] == true then
            output << JSON.pretty_generate(result)
        else
            output << JSON.generate(result)
        end

    end
    
    module_function :parse
    module_function :convert
    
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
csv2json-0.3.0 lib/csv2json.rb