简体   繁体   中英

Python serialization Error

When my python code trying to convert a dictionary object to Json string, it threw the following exception:

SerializationError: ({'status': 'rd', 
'name': 'Detecci\xf3nInt/.unclassified.ez', 'st': 0}, 
UnicodeDecodeError('utf8', 'Detecci\xf3nInt/.unclassified.ez', 7, 8, 
'invalid continuation byte'))

Any hints for fixing this problem please.

By default json.dump() uses UTF8 encoding, however, the value for the name key in your dictionary is not UTF8. It looks like one of the ISO-8859-X encodings. You can specify the encoding with the encoding parameter:

import json
d = {'status': 'rd', 'name': 'Detecci\xf3nInt/.unclassified.ez', 'st': 0}
s = json.dumps(d, encoding='ISO-8859-1')
print(s)

Output

{"status": "rd", "name": "Detecci\u00f3nInt/.unclassified.ez", "st": 0}

I had a bit of a guess as to which encoding to use, so you might want to check which is the correct encoding for your data.

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