Class: JsonNormalizer
- Inherits:
-
Object
- Object
- JsonNormalizer
- Defined in:
- lib/json_normalizer.rb
Instance Method Summary collapse
- #fetch_key(key) ⇒ Object
-
#initialize(map) ⇒ JsonNormalizer
constructor
Init requires pre defined JSON map.
- #key_contained?(key) ⇒ Boolean
- #swap_key(json, key) ⇒ Object
- #translate(json) ⇒ Object
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
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 49 50 51 52 53 54 |
# File 'lib/json_normalizer.rb', line 28 def translate(json) # json = JSON.parse(json) if !json.is_a?(Hash) json = JSON.parse(json) if ![Hash, Array].include?(json.class) if json.is_a?(Array) json.each do |j| j.keys.each do |key| if j[key].respond_to?(:each) self.translate(j[key]) self.swap_key(j, key) else self.swap_key(j, key) end end end else json.keys.each do |key| if json[key].respond_to?(:each) self.translate(json[key]) self.swap_key(json, key) else self.swap_key(json, key) end end end json end |