简体   繁体   中英

how to set proper encoding for json.load

I have been trying to load json this way:

data = json.load(f)

For some reasons that JSON has windows1251 encoding. So trying opening it causes error:

File "./labelme2voc.py", line 252, in main
    data = json.load(f)
  File "/home/dex/anaconda3/lib/python3.6/json/__init__.py", line 296, in load
    return loads(fp.read(),
  File "/home/dex/anaconda3/lib/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 81: invalid continuation byte

How can I fix that? JSON load doesn't have such option to encoding be specified

Try this:

import json

filename = ...  # specify filename here

with open(filename, encoding='cp1252') as f:
    data = json.loads(f.read())

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