什么是JSON:
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。现在很多服务器返回的结果都是json格式。主要是由于它比较容易解析和生成。JSON格式的数据本质上一种被格式化了的字符串。
JSON 语法规则
- 数据为 键/值 对。
- 数据由逗号分隔。
- 大括号保存对象
- 方括号保存数组
python 自带json 模块,提供了一种很简单的方式来编码和解码JSON数据。 其中两个主要的函数是 json.dumps() 和 json.loads()
JSON字符串用json.dumps, json.loads JSON文件名用json.dump, json.load
1.json.dumps()将一个Python格式的数据结构 序列化 为JSON格式的字符串:
import json
data = {
'stu_id':1,
'stu_name':'haha',
'a':[1,2,3]
}
json_str = json.dumps(data)
print(type(json_str),json_str)
输出结果:<class 'str'> {"stu_id": 1, "stu_name": "haha", "a": [1, 2, 3]}
2.json.loads()将一个JSON格式的字符串 反序列化 为一个Python格式的数据结构:
data = json.loads(json_str)
print(type(data),data)
输出结果:<class 'dict'> {'stu_id': 1, 'stu_name': 'haha', 'a': [1, 2, 3]}
3.json.dump() 和 json.load() 主要用来处理JSON文件读写。
json.dump(obj,fp) ->obj数据对象,fp文件对象
json.dump是写入数据到json文件中
第一种方法:
with open('test.json','w')as f:
json.dump(data,f)
第二中方法:
json_str = json.dumps(data)
with open('test.json','w')as f:
f.write(json_str)
json.load(f)读取json文件中的数据。
with open('test.json','r')as f:
data=json.load(f)
print(type(data),data)
输出结果:<class 'dict'> {'stu_id': 1, 'stu_name': 'haha', 'a': [1, 2, 3]}
4、open()和with open()的区别
open
1,打开文件
file=open(“文件名”,“读写模式”)
2,操作文件
3,关闭文件
file.close()
注意事项:
使用open方法,文件操作完毕之后必须关闭,否则长期保持对文件的连接状态,造成内存溢出的现象发生。
with open
1,打开文件
with open (“文件名”,“读写模式”) as file:
2,操作文件
3,关闭文件(自动关闭)