Class: JsonCsv

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

Constant Summary collapse

VERSION =
"0.5.2"
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.



103
104
105
# File 'lib/json-csv.rb', line 103

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

Class Method Details

.convert_csv_to_json(opts) ⇒ Object



97
98
99
# File 'lib/json-csv.rb', line 97

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

.convert_json_to_csv(opts) ⇒ Object



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

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

.new_from_argv(argv) ⇒ Object



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

def new_from_argv(argv)
  opts = parse_argv(argv)
  self.new(opts)
end

.parse_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
# File 'lib/json-csv.rb', line 32

def parse_argv(argv)
  opts = DEFAULT_OPTS

  argv = OptionParser.new do |op|
    op.banner = "Converts JSON to CSV, and vice versa.\nUsage: \#{$0} [options] [--] [input-file [output-file]]\n    EOT\n\n    op.on(\"-i input-file\", \"--input input-file\", \"Input file (default STDIN)\") do |input_file|\n      opts[:input_file] = input_file\n    end\n\n    op.on(\"-o output-file\", \"--output output-file\", \"Output file (default STDOUT)\") do |output_file|\n      opts[:output_file] = output_file\n    end\n\n    op.on(\"-s json|csv\", \"--source-encoding json|csv\", \"Encoding of input file (default json)\") do |source|\n      opts[:source_encoding] = source\n    end\n\n    op.on(\"-d depth\", \"--depth depth\", \"Maximum depth of JSON-to-CSV conversion (default -1, unlimited)\") do |depth|\n      opts[:depth] = depth.to_i\n    end\n\n    op.on(\"-e crlf|cr|lf\", \"--line-ending crlf|cr|lf\", \"Line endings for output file (default crlf).\") do |ending|\n      opts[:line_ending] = {\"crlf\" => \"\\r\\n\", \"cr\" => \"\\r\", \"lf\" => \"\\n\"}[ending]\n      if !opts[:line_ending]\n        STDERR.puts \"Invalid line ending '\#{ending}'.  Valid choices: crlf cr lf\"\n        exit 1\n      end\n    end\n\n    op.on_tail(\"--debug\", \"Turn debugging messages on\") do\n      opts[:debug] = true\n    end\n\n    op.on_tail(\"--version\", \"Print version info and exit\") do\n      puts \"json-csv version \#{VERSION} (\#{VERSION_DATE})\"\n      puts \"https://github.com/appcues/json-csv\"\n      exit\n    end\n\n    op.on_tail(\"-h\", \"--help\", \"Show this message and exit\") do\n      puts op.to_s\n      exit\n    end\n\n  end.parse(argv)\n\n  opts[:input_file] = argv.shift if argv.count > 0\n  opts[:output_file] = argv.shift if argv.count > 0\n\n  opts\nend\n"

Instance Method Details

#convert_csv_to_json(opts = {}) ⇒ Object

Raises:



171
172
173
# File 'lib/json-csv.rb', line 171

def convert_csv_to_json(opts = {})
  raise NotImplementedError
end

#convert_json_to_csv(opts = {}) ⇒ Object



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
160
161
162
163
164
165
166
167
168
169
# File 'lib/json-csv.rb', line 124

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.")
  depth = opts[:depth]
  depth += 1 if depth > 0  # a fudge, in order to use -1 as infinity
  headers = get_headers_from_json(input_fh, tmp_fh, 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, opts[:line_ending])
  data_fh.close
  output_fh.close

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

#run(opts = {}) ⇒ Object

Performs the JSON-to-CSV or CSV-to-JSON conversion, as specified in opts and the options passed in during JsonCsv.new.



110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/json-csv.rb', line 110

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