Class: JsonCsv

Inherits:
Object
  • Object
show all
Defined in:
lib/json-csv.rb

Constant Summary collapse

VERSION =
"0.5.1"
VERSION_DATE =
"2017-06-25"
DEFAULT_OPTS =
{
  input_file: "-",
  output_file: "-",
  source_encoding: "json",
  tmpdir: ENV['TMPDIR'] || "/tmp",
  debug: false,
  depth: -1,
  line_ending: "\r\n",
}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ JsonCsv

Returns a new instance of JsonCsv.



99
100
101
# File 'lib/json-csv.rb', line 99

def initialize(opts)
  @opts = DEFAULT_OPTS.merge(opts)
end

Class Method Details

.convert_csv_to_json(opts) ⇒ Object



94
95
96
# File 'lib/json-csv.rb', line 94

def convert_csv_to_json(opts)
  self.new(opts).convert_csv_to_json()
end

.convert_json_to_csv(opts) ⇒ Object



90
91
92
# File 'lib/json-csv.rb', line 90

def convert_json_to_csv(opts)
  self.new(opts).convert_json_to_csv()
end

.new_from_argv(argv) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/json-csv.rb', line 32

def new_from_argv(argv)
  opts = DEFAULT_OPTS

  OptionParser.new do |op|
    op.banner = <<-EOT
  Converts JSON to CSV, and vice versa.
  Usage: #{$0} [options] [--] [input-file [output-file]]
    EOT

    op.on("-i input-file", "--input input-file", "Input file (default STDIN)") do |input_file|
      opts[:input_file] = input_file
    end

    op.on("-o output-file", "--output output-file", "Output file (default STDOUT)") do |output_file|
      opts[:output_file] = output_file
    end

    op.on("-s json|csv", "--source-encoding json|csv", "Encoding of input file (default json)") do |source|
      opts[:source_encoding] = source
    end

    op.on("-d depth", "--depth depth", "Maximum depth of JSON-to-CSV conversion (default -1, unlimited)") do |depth|
      opts[:depth] = depth.to_i
      opts[:depth] += 1 if opts[:depth] > 0  # this is a fudge to use -1 as infinity
    end

    op.on("-e crlf|cr|lf", "--line-ending crlf|cr|lf", "Line endings for output file (default crlf).") do |ending|
      opts[:line_ending] = {"crlf" => "\r\n", "cr" => "\r", "lf" => "\n"}[ending]
      if !opts[:line_ending]
        STDERR.puts "Invalid line ending '#{ending}'.  Valid choices: crlf cr lf"
        exit 1
      end
    end

    op.on_tail("--debug", "Turn debugging messages on") do
      opts[:debug] = true
    end

    op.on_tail("--version", "Print version info and exit") do
      puts "json-csv version #{VERSION} (#{VERSION_DATE})"
      puts "https://github.com/appcues/json-csv"
      exit
    end

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

  end.parse!(argv)


  opts[:input_file] = argv.shift if argv.count > 0
  opts[:output_file] = argv.shift if argv.count > 0

  self.new(opts)
end

Instance Method Details

#convert_csv_to_json(opts = {}) ⇒ Object

Raises:

  • (NotImplementedError)


161
162
163
# File 'lib/json-csv.rb', line 161

def convert_csv_to_json(opts = {})
  raise NotImplementedError
end

#convert_json_to_csv(opts = {}) ⇒ Object



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/json-csv.rb', line 116

def convert_json_to_csv(opts = {})
  opts = @opts.merge(opts)

  ## First pass -- create CSV headers from JSON input
  input_fh = nil
  tmp_fh = nil
  tmp_filename = nil
  data_filename = nil

  if opts[:input_file] == "-"
    input_fh = STDIN
    data_filename = tmp_filename = "#{opts[:tmpdir]}/json-csv-#{$$}.tmp"
    debug(opts, "STDIN will be written to #{tmp_filename}.")
    tmp_fh = File.open(data_filename, "w")
  else
    input_fh = File.open(opts[:input_file], "r")
    data_filename = opts[:input_file]
  end

  debug(opts, "Getting headers from JSON data.")
  headers = get_headers_from_json(input_fh, tmp_fh, opts[:depth])

  input_fh.close
  tmp_fh.close if tmp_fh


  ## Second pass -- write CSV data from JSON input
  data_fh = File.open(data_filename, "r")
  output_fh = nil

  if opts[:output_file] == "-"
    output_fh = STDOUT
  else
    output_fh = File.open(opts[:output_file], "w")
  end

  debug(opts, "Writing CSV output.")
  output_csv(headers, data_fh, output_fh)
  data_fh.close
  output_fh.close

  debug(opts, "Removing #{tmp_filename}.")
  File.unlink(tmp_filename) if tmp_filename
end

#run(opts = {}) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/json-csv.rb', line 103

def run(opts = {})
  opts = @opts.merge(opts)
  enc = opts[:source_encoding]
  if enc == "json"
    convert_json_to_csv()
  elsif enc == "csv"
    convert_csv_to_json()
  else
    STDERR.puts "no such source encoding '#{enc}'"
    exit 1
  end
end