class EvocCLI::Util

Public Instance Methods

json2csv(path) click to toggle source
# 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