I dump dict object using json.dump
. To avoid UnicodeDecodeError
, I set ensure_ascii=False
following this advice.
with open(my_file_path, "w") as f:
f.write(json.dumps(my_dict, ensure_ascii=False))
The dump file has been successfully created, but when loading the dumped file UnicodeDecodeError happens:
with open(my_file_path, "r") as f:
return json.loads(f.read())
How to avoid UnicodeDecodeError
on loading the dump file?
Error message and stacktrace
The Error message is UnicodeDecodeError: 'utf8' codec can't decode byte 0x93 in position 0: invalid start byte
and stacktrace is:
/Users/name/.pyenv/versions/anaconda-2.0.1/python.app/Contents/lib/python2.7/json/__init__.pyc in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
336 if (cls is None and encoding is None and object_hook is None and
337 parse_int is None and parse_float is None and
--> 338 parse_constant is None and object_pairs_hook is None and not kw):
339 return _default_decoder.decode(s)
340 if cls is None:
/Users/name/.pyenv/versions/anaconda-2.0.1/python.app/Contents/lib/python2.7/json/decoder.pyc in decode(self, s, _w)
364 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
365 end = _w(s, end).end()
--> 366 if end != len(s):
367 raise ValueError(errmsg("Extra data", s, end, len(s)))
368 return obj
/Users/name/.pyenv/versions/anaconda-2.0.1/python.app/Contents/lib/python2.7/json/decoder.pyc in raw_decode(self, s, idx)
380 obj, end = self.scan_once(s, idx)
381 except StopIteration:
--> 382 raise ValueError("No JSON object could be decoded")
383 return obj, end
UnicodeDecodeError: 'utf8' codec can't decode byte 0x93 in position 0: invalid start byte