Python JSON 讀寫值,中文亂碼問題


JSON 文件

文件名稱為“TestJson.json”

{
    "test": "KEYtest",
    "testkv": {
        "testBoll": true,
        "testInt": 5643,
        "testStr": "被修改",
        "testfloat": 1.234,
        "testList": [1, 2, 3, 4],
        "testtupl": {"v1": 1, "v2": "Str2", "v3list": [3]},
        "testNone": null
    }
}

測試程序

import json
#讀取文件
with open('TestJson.json', 'r',encoding='utf-8') as fr:#
    jsonAll = json.load(fr)
    print(jsonAll)
    #修改某鍵下的值
    jsonAll['testkv']['testStr'] = "被修改"
    jsonAll['testkv']['testInt'] = 5643
    #獲取鍵下的值
    s = jsonAll['testkv']['testStr']
    print(s)

#寫入文件
with open('TestJson.json', 'w+',encoding='utf-8') as fw:
    json.dump(jsonAll, fw,indent=4,ensure_ascii=False)

  關於pyacharm 亂碼問題

pycharm 默認將Json文件保存為JBK 編碼,所以pycharm下運行時需要設置一下,如下圖:改為UTF-8。

 

 參考鏈接:

https://www.runoob.com/python3/python3-json.html

https://www.php.cn/python-tutorials-368530.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM