Sha256: c39eff6314b5dcfa698f83c74dcda0eb691d5f739932db174ca4cf5f310a8329

Contents?: true

Size: 1.83 KB

Versions: 1

Compression:

Stored size: 1.83 KB

Contents

#!/usr/bin/env ruby

require "rubygems"
require 'optparse'
require 'ostruct'
require File.join(File.expand_path(File.dirname(__FILE__)), '..', 'lib', 'json2csv.rb') # this form is important for local development

module JSON2CSVRunner

    # command-line parsing
    COMMAND = File.basename($0)
    USAGE = "Usage: #{COMMAND} [INPUT] [OPTIONS]"

    options = OpenStruct.new
    options.output = "-"
    options.separator = ","
    options.headers = nil

    opts = OptionParser.new do |o|
        o.banner = USAGE
        o.separator ""
        o.separator "Specific options:"

        o.on("-s", "--separator SEP", "Set separator character surrounded by single quotes (default is ',')") do |sep|
            options.separator = sep
        end

        o.on("-o", "--output FILE", "Write output to a file") do |fn|
            options.output = fn
        end

        o.on("-H", "--headers HEADERS", "Supply sorted list of headers, by which to order the columns in the CSV. These must match the key names in the JSON.") do |headers|
            if headers then
                options.headers = headers.split(",")
            end
        end

        o.on_tail("-h", "--help", "Show this message") do
            puts o
            exit
        end

        o.on_tail("-v", "--version", "Show version") do
            puts CSV2JSON::VERSION
            exit
        end
    end

    begin
        opts.parse!(ARGV)
    rescue
        raise "Unable to parse options: #{$!}"
    end

    # initialize output handle
    if options.output == "-"
        OUT = $stdout.clone
    else
        OUT = File.open(options.output, "w")
    end
    
    if ARGV.size > 0
        IN = File.read(ARGV[0])
    else
        IN = STDIN.read
    end

    # run the command
    JSON2CSV.parse(IN, OUT, options.headers, {:col_sep => options.separator})
    
    # leave in peace
    OUT.flush
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
csv2json-0.3.0 bin/json2csv