python3 json數據包含中文的讀
- 2020 年 1 月 13 日
- 筆記
python3 默認的是UTF-8格式,但在在用dump寫入的時候仍然要注意:如下
import json data1 = { "TestId": "testcase001", "Method": "post", "Title": "登錄測試", "Desc": "登錄基準測試", "Url": "http://xxx.xxx.xxx.xx", "InputArg": { "username": "王小丫", "passwd": "123456", }, "Result": { "errorno": "0" } } with open('casedate.json', 'w', encoding='utf-8') as f: json.dump(data1, f, sort_keys=True, indent=4)
在打開文件的時候要加上encoding=『utf-8』,不然會顯示成亂碼,如下:
{ "Desc": "��¼������", "InputArg": { "passwd": "123456", "username": "��СѾ" }, "Method": "post", "Result": { "errorno": "0" }, "TestId": "testcase001", "Title": "��¼����", "Url": "http://xxx.xxx.xxx.xx" }
在dump的時候也加上ensure_ascii=False,不然會變成ascii碼寫到文件中,如下:
{ "Desc": "u767bu5f55u57fau51c6u6d4bu8bd5", "InputArg": { "passwd": "123456", "username": "u738bu5c0fu4e2b" }, "Method": "post", "Result": { "errorno": "0" }, "TestId": "testcase001", "Title": "u767bu5f55u6d4bu8bd5", "Url": "http://xxx.xxx.xxx.xx" }
另外python3在向txt文件寫中文的時候也要注意在打開的時候加上encoding=『utf-8』,不然也是亂碼,如下:
with open('result.txt', 'a+', encoding='utf-8') as rst: rst.write('return data') rst.write('|') for x in r.items(): rst.write(x[0]) rst.write(':')