Class: Json_Normalizer
- Inherits:
-
Object
- Object
- Json_Normalizer
- Defined in:
- lib/json_normalizer.rb
Instance Method Summary collapse
- #fetch_key(key) ⇒ Object
-
#initialize(map) ⇒ Json_Normalizer
constructor
Init requires pre defined JSON map.
- #key_contained?(key) ⇒ Boolean
- #swap_key(json, key) ⇒ Object
- #translate(json) ⇒ Object
Constructor Details
#initialize(map) ⇒ Json_Normalizer
Init requires pre defined JSON map. Ex. { “this_key”: [“morphed”, “to”, “this_key”] }
8 9 10 11 |
# File 'lib/json_normalizer.rb', line 8 def initialize(map) @map = JSON.parse(map) @result = {} end |
Instance Method Details
#fetch_key(key) ⇒ Object
18 19 20 |
# File 'lib/json_normalizer.rb', line 18 def fetch_key(key) @map.keys.each{ |k| return k if @map[k].include?(key) } end |
#key_contained?(key) ⇒ Boolean
13 14 15 16 |
# File 'lib/json_normalizer.rb', line 13 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
22 23 24 25 26 27 28 29 |
# File 'lib/json_normalizer.rb', line 22 def swap_key(json, key) if self.key_contained?(key) json[self.fetch_key(key).first] = json[key] json.delete(key) else # if we want to move out non-normalized keys into a different 'misc' key or something end end |
#translate(json) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/json_normalizer.rb', line 31 def translate(json) json = JSON.parse(json) if !json.is_a?(Hash) json.keys.each do |key| if json[key].respond_to?(:each) puts "Key: #{key} recursing..." self.translate(json[key]) self.swap_key(json, key) else self.swap_key(json, key) end end # json.map{ |k, v| [k.to_s, v] }.to_h JSON.parse json.to_json end |