drewkerrigan/nagios-http-json

Bytes encoding issue

Closed this issue · 4 comments

Hello, I had an issue with the encoding, I got some json_data as 'bytes' and not 'str':

./check_http_json.py -H X.X.X.X -P **** -p 'path' -f '.count' -c '...:' -t 15 -k
Traceback (most recent call last):
  File "check_http_json.py", line 644, in <module>
    main(sys.argv[1:])
  File "check_http_json.py", line 623, in main
    data = json.loads(json_data)
  File "/usr/lib/python3.5/json/__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'

JSON received:
b'{"count": 167}'

I resolved it by catching the encoding:

      json_data = response.read()
+     encoding = response.info().get_content_charset('utf-8')
...
-        data = json.loads(json_data)
+        data = json.loads(json_data.decode(encoding))

Hi, thanks for the hint. I'll have a look at it.

Cheers, Markus

Hi,

is it possible you are running Python 3.5 (or older)? Because this should not be an issue with Python 3.6 and newer: https://docs.python.org/3/whatsnew/3.6.html#json

docker run -ti --rm python:3.6
Python 3.6.12 (default, Nov 18 2020, 14:46:32) 
>>> import json
>>> json.loads('{"foo": 123}')
{'foo': 123}
>>> json.loads(b'{"foo": 123}')
{'foo': 123}
docker run -ti --rm python:3.5 
Python 3.5.10 (default, Sep 10 2020, 18:30:47) 
>>> import json
>>> json.loads('{"foo": 123}')
{'foo': 123}
>>> json.loads(b'{"foo": 123}')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/json/__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'

Python 3.5 has reached its end-of-life, so I will update the supported versions ins the README accordingly.

Hello, you're right, I was running on Python 3.5, sorry for the wrong track,