Module: JsonCsv::JsonToCsv

Included in:
JsonCsv
Defined in:
lib/json_csv/json_to_csv.rb

Instance Method Summary collapse

Instance Method Details

#flatten_hash(obj, parent_path = '', flat_hash_to_build = {}) ⇒ Object

This method calls itself recursively while flattening a hash, and during this sequence of calls the obj param may either be a hash or an array.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/json_csv/json_to_csv.rb', line 24

def flatten_hash(obj, parent_path = '', flat_hash_to_build = {})
  if obj.is_a?(Hash)
    obj.each do |key, val|
      if key_contains_unallowed_characters?(key)
        raise ArgumentError, 'Cannot deal with hash keys that contain "[" or "]" or "." because these characters have special meanings in CSV headers.'
      end
      path = parent_path + (parent_path.empty? ? '' : '.') + key
      flatten_hash(val, path, flat_hash_to_build)
    end
  elsif obj.is_a?(Array)
    obj.each_with_index do |el, index|
      path = parent_path + "[#{index}]"
      flatten_hash(el, path, flat_hash_to_build)
    end
  else
    flat_hash_to_build[parent_path] = obj unless obj.nil? || obj == '' # ignore nil or empty string values
  end

  flat_hash_to_build
end

#json_hash_to_flat_csv_row_hash(json_hash, array_notation = JsonCsv::ArrayNotation::BRACKETS) ⇒ Object

Converts the given json_hash into a flat csv hash, converting all values to strings (because CSVs are dumb and don’t store info about data types) Set first_index to 1 if you want the first element in an array to



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/json_csv/json_to_csv.rb', line 10

def json_hash_to_flat_csv_row_hash(json_hash, array_notation = JsonCsv::ArrayNotation::BRACKETS)
  flat = flatten_hash(json_hash)
  # Convert values to strings because in the CSV file, all values are strings
  flat.each { |key, val| flat[key] = val.nil? ? '' : val.to_s }
  # If we're using dash array notation, convert the headers
  if array_notation == JsonCsv::ArrayNotation::DASH
    Hash[flat.map { |key, val| [JsonCsv::ArrayNotation.bracket_header_to_dash_header(key), val] }]
  else
    flat
  end
end

#key_contains_unallowed_characters?(key) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
48
# File 'lib/json_csv/json_to_csv.rb', line 45

def key_contains_unallowed_characters?(key)
  return true if key.index('[') || key.index(']') || key.index('.')
  false
end