Skip to content

Instantly share code, notes, and snippets.

@icy
Created December 11, 2017 04:00
Show Gist options
  • Save icy/81d32c723dff187a51c77a2120ecb2ae to your computer and use it in GitHub Desktop.
Save icy/81d32c723dff187a51c77a2120ecb2ae to your computer and use it in GitHub Desktop.
flatten_with_path.rb
# https://stackoverflow.com/questions/10712679/flatten-a-nested-json-object
# My Fixes
#
# Input: {"twitter":{"aliases":{"twitter_alias":{}}}}
# Old Ouput: {}
# New Input: twitter.aliases.twitter_alias: <EMPTY>
#
module Enumerable
def flatten_with_path(parent_prefix = nil)
res = {}
self.each_with_index do |elem, i|
if elem.is_a?(Array)
k, v = elem
else
k, v = i, elem
end
key = parent_prefix ? "#{parent_prefix}.#{k}" : k # assign key name for result hash
if v.is_a?(Enumerable)
res2 = v.flatten_with_path(key)
res2 = {key => "<EMPTY>"} if res2.nil? or res2.empty?
res.merge!(res2) # recursive call to flatten child elements
else
res[key] = v
end
end
res
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment