class JsonToCsv::Convert
Public Class Methods
new(filepath)
click to toggle source
# File lib/json_to_csv/convert.rb, line 6 def initialize(filepath) @filepath = filepath convert end
Private Instance Methods
build_headers()
click to toggle source
# File lib/json_to_csv/convert.rb, line 26 def build_headers object = @parsed_json.first @headers = retrieve_object_keys(object) end
build_object_csv_row(object)
click to toggle source
# File lib/json_to_csv/convert.rb, line 61 def build_object_csv_row(object) values = @headers.map do |path| retrieve_value(object, path) end end
compute_value(value)
click to toggle source
# File lib/json_to_csv/convert.rb, line 76 def compute_value(value) return value unless value.is_a?(Array) value.join(",") end
convert()
click to toggle source
# File lib/json_to_csv/convert.rb, line 13 def convert read_and_parse_json_file build_headers generate_csv_filepath write_into_csv_file end
generate_csv_filepath()
click to toggle source
# File lib/json_to_csv/convert.rb, line 47 def generate_csv_filepath @csv_filepath = "#{@path}.csv" end
read_and_parse_json_file()
click to toggle source
# File lib/json_to_csv/convert.rb, line 20 def read_and_parse_json_file response = File.read(@filepath) @path = File.basename(@filepath, ".*") @parsed_json = JSON.parse(response) end
retrieve_object_keys(object, path = nil)
click to toggle source
# File lib/json_to_csv/convert.rb, line 31 def retrieve_object_keys(object, path = nil) response = object.map do |key, value| if value.is_a?(Hash) full_path = path ? "#{path}.#{key}" : key retrieve_object_keys(value, full_path) else if path && !path.nil? "#{path}.#{key}" else key end end end response.compact.flatten end
retrieve_value(object, header)
click to toggle source
# File lib/json_to_csv/convert.rb, line 67 def retrieve_value(object, header) path_keys = header.split('.') path_keys.each do |path_key| return nil if object.nil? object = object[path_key] end value = compute_value(object) end
write_into_csv_file()
click to toggle source
# File lib/json_to_csv/convert.rb, line 51 def write_into_csv_file csv_options = { col_sep: ',', quote_char: '"' } CSV.open(@csv_filepath, 'w+', csv_options) do |csv| csv << @headers @parsed_json.each do |object| csv << build_object_csv_row(object) end end end