Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ericboehs
Created August 19, 2021 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericboehs/caaa6c82a16d3e4548bb5aea7ec0c2db to your computer and use it in GitHub Desktop.
Save ericboehs/caaa6c82a16d3e4548bb5aea7ec0c2db to your computer and use it in GitHub Desktop.
Flatten a JSON object (for Slack)
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