Skip to content

Instantly share code, notes, and snippets.

@ftuyama
Created September 28, 2021 15:37
Show Gist options
  • Save ftuyama/5bf916d052cb35e38236f357880b8628 to your computer and use it in GitHub Desktop.
Save ftuyama/5bf916d052cb35e38236f357880b8628 to your computer and use it in GitHub Desktop.
Recursive flattening json object
def flatten_hash(param, prefix=nil)
param.each_pair.reduce({}) do |a, (k, v)|
if v.is_a?(Array)
v = v.map.with_index { |x, i| [i, x] }.to_h
end
if v.is_a?(Hash)
a.merge(flatten_hash(v, "#{prefix}#{k}."))
else
a.merge("#{prefix}#{k}".to_sym => v)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment