Created
August 19, 2021 18:46
-
-
Save ericboehs/caaa6c82a16d3e4548bb5aea7ec0c2db to your computer and use it in GitHub Desktop.
Flatten a JSON object (for Slack)
This file contains 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
require 'json' | |
def flatten_hash(hash) | |
hash.each_with_object({}) do |(k, v), h| | |
if v.is_a? Hash | |
flatten_hash(v).map { |h_k, h_v| h["#{k}.#{h_k}".to_sym] = h_v } | |
else | |
h[k] = v | |
end | |
end | |
end | |
json_raw = %({ "user": { "id": "foo", "bar": "baz" }, "id": 123 }) | |
json = JSON.parse json_raw | |
puts flatten_hash(json).to_json |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment