网络编程
位置:首页>> 网络编程>> Python编程>> 详解python读写json文件

详解python读写json文件

作者:liulanba  发布时间:2022-11-01 16:18:53 

标签:python,读写,json,文件

python处理json文本文件主要是以下四个函数:

函数作用
json.dumps对数据进行编码,将python中的字典 转换为 字符串
json.loads对数据进行解码,将 字符串 转换为 python中的字典
json.dump将dict数据写入json文件中
json.load打开json文件,并把字符串转换为python的dict数据

json.dumps / json.loads

数据转换对照:

jsonpython


objectdict
arraylist
stringstr
number (int)int
number (real)float
trueTrue
falseFalse
nullNone

代码示例:


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'>

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!

来源:https://blog.csdn.net/liulanba/article/details/121963892

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com