Module: CSV2JSON
- Defined in:
- lib/csv2json.rb,
lib/csv2json-version.rb
Constant Summary collapse
- VERSION =
"0.3.0"
Class Method Summary collapse
-
.convert(val) ⇒ Object
convert an input string value to integer or float if applicable.
-
.parse(input, output, headers = nil, csvOptions = {}, gemOptions = {}) ⇒ Object
input and output are file objects, you can use StringIO if you want to work in memory.
Class Method Details
.convert(val) ⇒ Object
convert an input string value to integer or float if applicable
10 11 12 13 |
# File 'lib/csv2json.rb', line 10 def convert(val) return Integer(val) if val.to_i.to_s == val Float(val) rescue val end |
.parse(input, output, headers = nil, csvOptions = {}, gemOptions = {}) ⇒ Object
input and output are file objects, you can use StringIO if you want to work in memory
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/csv2json.rb', line 16 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 |