當嘗試進行中文輸出的時候,基本打印出來的情況都是亂碼,這個時候應該怎麼解決?
網上非常多版本的解決方法都是老舊沒有更新,大家嘗試過後相信都會報這樣一個錯誤:
TypeError: __init__() got an unexpected keyword argument ‘encoding'
這個原因就是在 python3 中,json.dumps() 中壓根就沒有 encoding 這個參數
下面是它的 API doc,可以看下:
json.dumps(obj, *, skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
解決方法:
1- python2 版本:利用json.dumps進行轉換
import json
s = '你好啊'
print(json.dumps(s, encoding='UTF-8', ensure_ascii=False))
2- python3 版本:直接在寫入文件的是否加上encoding這個參數
with open('filename.json', 'w', encoding="utf-8") as f:
f.write(json.dumps(dicts, ensure_ascii=False))
上面的dicts就是你要寫入的內容。
轉自: https://blog.csdn.net/weixin_43509263/article/details/90203694