Class: EvocCLI::Util

Inherits:
Thor
  • Object
show all
Defined in:
lib/evoc_cli/util.rb

Instance Method Summary collapse

Instance Method Details

#json2csv(path) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/evoc_cli/util.rb', line 8

def json2csv(path)
    json = nil
    if File.extname(path) == '.gz'
      Zlib::GzipReader.open(path) {|gz|
        json = gz.read
      }
    else
      json = File.read(path,external_encoding: 'iso-8859-1',internal_encoding: 'utf-8')
    end
    header = []
    header_not_written = true
   JSON.parse(json).each do |json_object|
     if header_not_written
       header = json_object.keys
       options[:exclude_columns].each {|c| header.delete(c)}
       CSV {|row| row << header}
       header_not_written = false
     end
     # remove unwanted keys
     options[:exclude_columns].each {|c| json_object.delete(c)}
     if json_object.keys == header
     CSV {|row| row << json_object.values.map {|v| v.is_a?(Array) ? v.join(",") : v }}
     else
       raise ArgumentError, "CSV header (made from first json object) didn't match with the keys in the current json object, the keys were: #{json_object.keys}"
     end
   end
end