-
-
Save rajbacharya/50556dde3209cd09fdd214b7498ac2ab to your computer and use it in GitHub Desktop.
Flatten ruby hash, Could be used to convert nested ruby hash (or json) to csv
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
| def flatten_hash(hash, results = {}, parent_key = '') | |
| return results unless hash.kind_of?(Hash) | |
| hash.keys.each do |key| | |
| # current_key = "#{parent_key}[#{key}]" # uncomment this if you want to keep parent key as a partof key for flattened hash (csv column name) | |
| current_key = key | |
| if hash[key].kind_of?(Hash) | |
| results = flatten_hash(hash[key], results, current_key) | |
| else | |
| if hash[key].kind_of?(Array) | |
| results[current_key] = hash[key].reject(&:empty?).join("; ") | |
| else | |
| results[current_key] = hash[key] | |
| end | |
| end | |
| end | |
| results | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment