脚本宝典收集整理的这篇文章主要介绍了详解python读写json文件,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
python处理json文本文件主要是以下四个函数:
函数 | 作用 |
---|---|
json.dumps | 对数据进行编码,将python中的字典 转换为 字符串 |
json.loads | 对数据进行解码,将 字符串 转换为 python中的字典 |
json.dump | 将dict数据写入json文件中 |
json.load | 打开json文件,并把字符串转换为python的dict数据 |
json.dumps / json.loads
数据转换对照:
json | python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
代码示例:
import json tesdic = { 'name': 'Tom', 'age': 18, 'score': { 'math': 98, 'chinese': 99 } } PRint(tyPE(tesdic)) json_str = json.dumps(tesdic) print(json_str) print(type(json_str)) newdic = json.loads(json_str) print(newdic) print(type(newdic))
输出为:
<class 'dict'> {"name": "Tom", "age": 18, "score": {"math": 98, "chinese": 99}} <class 'str'> {'name': 'Tom', 'age': 18, 'score': {'math': 98, 'chinese': 99}} <class 'dict'>
json.dump / json.load
写入json的内容只能是dict类型,字符串类型的将会导致写入格式问题:
wITh open("res.json", 'w', encoding='utf-8') as fw: json.dump(json_str, fw, indent=4, ensure_ascii=False)
则json文件内容为:
"{\"name\": \"Tom\", \"age\": 18, \"score\": {\"math\": 98, \"chinese\": 99}}"
我们换一种数据类型写入:
with open("res.json", 'w', encoding='utf-8') as fw: json.dump(tesdic, fw, indent=4, ensure_ascii=False)
则生成的josn就是正确的格式:
{ "name": "Tom", "age": 18, "score": { "math": 98, "chinese": 99 } }
同理,从json中读取到的数据也是dict类型:
with open("res.json", 'r', encoding='utf-8') as fw: inJSON = json.load(fw) print(injson) print(type(injson))
{'name': 'Tom', 'age': 18, 'score': {'math': 98, 'chinese': 99}} <class 'dict'>
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本宝典的更多内容!
以上是脚本宝典为你收集整理的详解python读写json文件全部内容,希望文章能够帮你解决详解python读写json文件所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。