Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Switching off pretty formatting by default (as one--line output is ea…

…sier to script against) - added option -p to switch it back on
  • Loading branch information...
commit 18d183f752d864da1f903ee3bdc8c1e756b18ae4 1 parent 0436af7
rory authored
Showing with 16 additions and 5 deletions.
  1. +7 −2 bin/csv2json
  2. +9 −3 lib/csv2json.rb
View
9 bin/csv2json
@@ -6,7 +6,7 @@ require 'ostruct'
require File.join(File.expand_path(File.dirname(__FILE__)), '..', 'lib', 'csv2json.rb') # this form is important for local development
module CSV2JSONRunner
-
+
# command-line parsing
COMMAND = File.basename($0)
USAGE = "Usage: #{COMMAND} [INPUT] [OPTIONS]"
@@ -14,6 +14,7 @@ module CSV2JSONRunner
options = OpenStruct.new
options.output = "-"
options.separator = ","
+ options.pretty = false
opts = OptionParser.new do |o|
o.banner = USAGE
@@ -28,6 +29,10 @@ module CSV2JSONRunner
options.output = fn
end
+ o.on("-p", "--pretty", "Pretty-format JSON output") do
+ options.pretty = true
+ end
+
o.on_tail("-h", "--help", "Show this message") do
puts o
exit
@@ -59,7 +64,7 @@ module CSV2JSONRunner
end
# run the command
- CSV2JSON.parse(IN, OUT, nil, :col_sep => options.separator)
+ CSV2JSON.parse(IN, OUT, nil, {:col_sep => options.separator}, {:pretty => options.pretty})
# leave in peace
OUT.flush
View
12 lib/csv2json.rb
@@ -1,3 +1,4 @@
+require 'rubygems'
require 'fastercsv'
require 'json'
require 'csv2json-version.rb'
@@ -11,10 +12,10 @@ def convert(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, options={})
+ def parse(input, output, headers=nil, csvOptions={}, gemOptions={})
result = Array.new
- FasterCSV.new(input, options).each do |row|
+ FasterCSV.new(input, csvOptions).each do |row|
# treat first row as headers if the caller didn't provide them
unless headers
headers = row
@@ -27,7 +28,12 @@ def parse(input, output, headers=nil, options={})
result << snippet
end
- output << JSON.pretty_generate(result)
+ if gemOptions[:pretty] == true then
+ output << JSON.pretty_generate(result)
+ else
+ output << JSON.generate(result)
+ end
+
end
module_function :parse
Please sign in to comment.
Something went wrong with that request. Please try again.