Skip to content

Commit

Permalink
now can flatten json arrays along with hashes
Browse files Browse the repository at this point in the history
  • Loading branch information
adamfeuer committed Feb 27, 2012
1 parent 7410246 commit 04735ad
Showing 1 changed file with 23 additions and 15 deletions.
38 changes: 23 additions & 15 deletions check_http_json.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
# URL: github.com/phrawzty/check_http_json
# Description: Nagios plugin that makes an HTTP connection and looks for some JSON or summat.



# Requires.
require 'rubygems'
require 'json'
Expand All @@ -14,13 +12,9 @@
require 'optparse'
require 'timeout'



# Herp derp.
options = {}



# Def jam.

# Display verbose output (if being run by a human for example).
Expand All @@ -39,16 +33,30 @@ def do_exit (v, code)
end
end

# As the results may be nested hashes; flatten that out into something manageable.
def val_flatten(val, newkey = nil, flat = {})
if val.is_a? Hash then
hash_flatten val, newkey, flat
else
flat[newkey] = val
end
end

# As the results may be arrays or nested hashes; flatten that out into something manageable.
def hash_flatten(hash, prefix = nil, flat = {})
hash.keys.each do |key|
newkey = key
newkey = '%s.%s' % [prefix, key] if prefix
val = hash[key]
if val.is_a? Hash then
hash_flatten val, newkey, flat
else
flat[newkey] = val
if hash.is_a? Array
hash.each_index do |index|
newkey = index
newkey = nil if hash.length == 1
newkey = prefix if prefix
val = hash[index]
val_flatten val, newkey, flat
end
else
hash.keys.each do |key|
newkey = key
newkey = '%s.%s' % [prefix, key] if prefix
val = hash[key]
val_flatten val, newkey, flat
end
end
return flat
Expand Down

1 comment on commit 04735ad

@phrawzty
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Solid idea ! Feel free to open a pull request. :)

Please sign in to comment.