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