我有一個 json 檔案,我想打開(讀取和寫入)它們而不顯示為 unicode :
json檔案如下:
{"A":"\u0e16"}
{"B":"\u0e39"}
{"C":"\u0e43\u0e08\u0e27"}
我嘗試了下面的代碼但不起作用(仍以編碼的 unicode 形式打開):
with open("test.json",encoding='utf8') as in_data:
for line in in_data:
print(line)
預期輸出:
{"A":"?"}
{"B":"??"}
{"C":"???"}
uj5u.com熱心網友回復:
該檔案不是有效的 JSON,而是所謂的“JSON 行格式”,其中每一行都是有效的 JSON。您還需要解碼 JSON 行以正確顯示它。該json.loads()函式接受一個字串并將其解碼為 JSON:
import json
with open("test.json",encoding='utf8') as in_data:
for line in in_data:
print(json.loads(line))
輸出:
{'A': '?'}
{'B': '?'}
{'C': '???'}
uj5u.com熱心網友回復:
使用 json 檔案時,您必須在使用之前對其進行解碼:首先import json
然后:
with open("jason.json", encoding="utf-8") as in_data:
dict_from_json = json.load(in_data)
for k, v in dict_from_json.items():
print(k, v)
此外,您可以將 for 回圈放在with open塊外
如果你想按原樣解碼它,你的 json 檔案中也有一個錯誤,它應該這樣寫:
{"A":"\u0e16 ",
"B":"\u0e39",
"C":"\u0e43\u0e08\u0e27"}
正如您在此處看到的,json 檔案必須是類似字典的物件或串列,您可以在檔案中閱讀有關它的更多資訊
uj5u.com熱心網友回復:
您打開了檔案但沒有閱讀它。要讀取檔案,您必須添加
lines=in_data.readlines()
在這之后你可以寫
for line in lines:
print(line)
還有它的 utf-8
uj5u.com熱心網友回復:
只是一個小錯誤,你必須使用encoding='utf-8'而不是 encoding='utf8 '
希望它能解決問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/376089.html
