简体   繁体   中英

JSON TypeError: expected string or buffer

I'm trying to store an exception error to json. Even though I'm pretty sure I'm storing a string, it's still giving me a typeerror.

Relevant section of code:

except ConnectionError as e:
        s = str(e)
        print type(s)
        data = json.loads({'error message': s})
        print "JSON load succeeded" 

Traceback:

<type 'str'>

Traceback (most recent call last):
  File "[REDACTED]", line 36, in <module>
    ping(SERVERS)
  File "[REDACTED]", line 29, in ping
    data = json.loads({'error message': s})
  File "C:\Python27\Lib\json\__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\Lib\json\decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

This is quite baffling to me. I'd appreciate any help with this matter.

You are looking for json.dumps() , not json.loads() . Try this:

    data = json.dumps({'error message': s})

json.dumps(obj) : Serialize obj to a JSON formatted str
json.loads(s) : Deserialize s (a str instance containing a JSON document) to a Python object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM