-
-
Save toothrot/787025 to your computer and use it in GitHub Desktop.
underscoring json in ruby
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 self.underscore_hash(hash) | |
| hash.inject({}) do |underscored, (key, value)| | |
| value = underscore_hash(value) if value.is_a?(Hash) | |
| value = value.map { |v| underscore_hash(v) } if value.is_a?(Array) | |
| underscored[key.underscore] = value | |
| underscored | |
| end | |
| end |
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 self.underscore_hash(hash) | |
| hash.inject({}) do |underscored, (key, value)| | |
| underscored[key.underscore] = case value | |
| when Hash: underscore_hash(value) | |
| when Array: value.map {|v| underscore_hash(v)} | |
| else value | |
| end | |
| underscored | |
| end | |
| end |
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 self.underscore_hash(camel_hash) | |
| camel_hash.inject({}) do |underscored, (key, value)| | |
| value = case value | |
| when Hash: underscore_hash(value) | |
| when Array: value.map {|v| underscore_hash(v)} | |
| else value | |
| end | |
| underscored[key.underscore] = value | |
| underscored | |
| end | |
| end |
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 self.underscore(json) | |
| case json | |
| when Hash | |
| json.inject({}) do |underscored, (key, value)| | |
| underscored[key.underscore] = underscore_hash(value) | |
| underscored | |
| end | |
| when Array | |
| json.map {|v| underscore_hash(v)} | |
| else | |
| json | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment