Last active
May 20, 2016 16:07
-
-
Save iamjwc/eb4121796ef3245946bf184c344e9cd8 to your computer and use it in GitHub Desktop.
Flattens hashes/arrays into a single level hash with the full json key path as a top level key. Useful for finding differences between two large manifests.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage: | |
# (irb)> { "some" => [{"keys" => "with", "some" => ["values"]}]}.flarp | |
# => {"some.0.keys"=>"with", "some.0.some.0"=>"values"} | |
class Hash | |
def flarp(h = {}, prefix = nil) | |
each do |k, v| | |
new_k = [prefix, k].compact.join(".") | |
if v.is_a?(Array) || v.is_a?(Hash) | |
v.flarp(h, new_k) | |
else | |
h[new_k] = v | |
end | |
end | |
h | |
end | |
end | |
class Array | |
def flarp(h = {}, prefix = nil) | |
each_with_index do |v, i| | |
new_k = [prefix, i].compact.join(".") | |
if v.is_a?(Array) || v.is_a?(Hash) | |
v.flarp(h, new_k) | |
else | |
h[new_k] = v | |
end | |
end | |
h | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment