Class: JsonNormalizer

Inherits:
Object
  • Object
show all
Defined in:
lib/json_normalizer.rb

Instance Method Summary collapse

Constructor Details

#initialize(map) ⇒ JsonNormalizer

Init requires pre defined JSON map. Ex. { “this_key”: [“morphed”, “to”, “this_key”] }



7
8
9
10
# File 'lib/json_normalizer.rb', line 7

def initialize(map)
  @map = JSON.parse(map)
  @result = {}
end

Instance Method Details

#fetch_key(key) ⇒ Object



17
18
19
# File 'lib/json_normalizer.rb', line 17

def fetch_key(key)
  @map.keys.each{ |k| return k if @map[k].include?(key) }
end

#key_contained?(key) ⇒ Boolean

Returns:

  • (Boolean)


12
13
14
15
# File 'lib/json_normalizer.rb', line 12

def key_contained?(key)
  @map.keys.each{ |k| return true if @map[k].include?(key.to_s) }
  return false
end

#swap_key(json, key) ⇒ Object



21
22
23
24
25
26
# File 'lib/json_normalizer.rb', line 21

def swap_key(json, key)
  if self.key_contained?(key)
    json[self.fetch_key(key)] = json[key]
    json.delete(key)
  end
end

#translate(json) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/json_normalizer.rb', line 28

def translate(json)
  json = JSON.parse(json) if ![Hash, Array].include?(json.class)
  if json.is_a?(Array)
    json.each do |j|
      translate(j)
    end
  else
    json.keys.each do |key|
      if json[key].is_a?(Array)
        translate(json[key])
        swap_key(json,key)
      else
        if json[key].respond_to?(:keys)
          translate(json[key])
        end
        swap_key(json,key)
      end
    end
  end
  json
end