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。
参考链接: