Skip to content

Commit

Permalink
Rework JsonHelper.get() to work with bracket in keys
Browse files Browse the repository at this point in the history
  • Loading branch information
martialblog committed Mar 22, 2024
1 parent ce9c5fd commit dfcdf4d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 13 deletions.
31 changes: 18 additions & 13 deletions check_http_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,25 +156,30 @@ def get(self, key, temp_data=''):
data = temp_data
else:
data = self.data

if len(key) <= 0:
return data
if key.find(self.separator) != -1 and \
key.find(self.arrayOpener) != -1:


if key.find(self.separator) != -1 and key.find(self.arrayOpener) != -1:
if key.find(self.separator) < key.find(self.arrayOpener):
return self.getSubElement(key, data)
else:
return self.getSubArrayElement(key, data)
else:
if key.find(self.separator) != -1:
return self.getSubElement(key, data)
else:
if key.find(self.arrayOpener) != -1:
return self.getSubArrayElement(key, data)
else:
if isinstance(data, dict) and key in data:
return data[key]
else:
return (None, 'not_found')

if key.find(self.separator) != -1:
return self.getSubElement(key, data)

if key.find(self.arrayOpener) != -1:
# If we got an arrayOpener but the next char is not [0-9] or * then it might just be a string
# This isn't optimal since this 'update (foobar)(0)' still won't work
if key[key.find(self.arrayOpener)+1].isnumeric() or key[key.find(self.arrayOpener)+1] == "*":
return self.getSubArrayElement(key, data)

if isinstance(data, dict) and key in data:
return data[key]

return (None, 'not_found')

def expandKey(self, key, keys):
if '(*)' not in key:
Expand Down
27 changes: 27 additions & 0 deletions test/test_check_http_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,3 +302,30 @@ def test_empty_key_value_array(self):
# This should throw an error
data = '[]'
self.check_data(rules.dash_q(['(*).update_status,warn_me']), data, CRITICAL_CODE)

def test_bracket_in_key(self):
"""
https://github.com/drewkerrigan/nagios-http-json/issues/76
"""

rules = RulesHelper()

# This should work
data = '[{"update status": "failure"}]'
self.check_data(rules.dash_q(['(*).update status,failure']), data, OK_CODE)

data = '[{"update (status)": "failure"}]'
self.check_data(rules.dash_q(['(*).update (status),failure']), data, OK_CODE)

data = '[{"update (((status)": "failure"}]'
self.check_data(rules.dash_q(['(*).update (((status),failure']), data, OK_CODE)

data = '[{"update )status)": "failure"}]'
self.check_data(rules.dash_q(['(*).update )status),failure']), data, OK_CODE)

data = '[{"update (status": "failure"}]'
self.check_data(rules.dash_q(['(*).update (status),failure']), data, WARNING_CODE)

# Does not yet work
# data = '{"update (foobar)": ["bar"]}'
# self.check_data(rules.dash_q(['update (foobar)(0),bar']), data, OK_CODE)

0 comments on commit dfcdf4d

Please sign in to comment.