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
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
31 32 33 34 35 36 |
# File 'lib/json_normalizer.rb', line 31 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
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/json_normalizer.rb', line 38 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) puts "Key: #{key} recursing..." 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) puts "Key: #{key} recursing..." self.translate(json[key]) self.swap_key(json, key) else self.swap_key(json, key) end end end # json.map{ |k, v| [k.to_s, v] }.to_h # JSON.parse json.to_json json end |