python json.dump() 中文报错问题

print json.dumps(a, indent=4, ensure_ascii=False)
可以正常输出中文

with open('filename', 'w') as f:
json.dump(a, f, indent=4, ensure_ascii=False)

报错UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-3: ordinal not in range(128)

解决

import codecs
with codecs.open ('filename', 'w', 'utf-8') as f :
json.dump(a, f, indent=4, ensure_ascii=False)

你可能感兴趣的:(python json.dump() 中文报错问题)