首先认识一下JSON格式:(两种格式)

  • 数组/集合格式: 类似于Python中列表套字典[{}, {}, {}]
    • [obj,obj,obj…]
  • 对象格式: 类似于Python中的字典{}格式
    • {“key1”:obj,”key2”:obj,”key3”:obj…}

s

四个函数实现JSON和Python之间的交互

※json.load 从json文件中加载数据(自动加载为python类型的数据
※json.dump 将python中的数据写入到json文件中
json.loads 把字符串类型的json数据转换为字典
json.dumps 把字符串类型的数据存储到json文件中

json.load

对Json文件进行读取

1
2
3
4
5
import json
with open("stu.json", "r", encoding="utf8") as f:
data = json.load(f)
print(data)
print(type(data))

json.dump

dump就是备份的意思, 将数据(列表嵌套字典)写入json文件

1
2
3
4
str = [{"id": 1, "name": "tom", "tel": "17628738431"},{"id": 2, "name": "jerry", "tel": "17628738431"}]
with open("stu.json", "w", encoding="utf8") as f:
json.dump(str, f)
f.close()

json.loads

把字符串类型的json数据转换为python中的字典

1
2
3
4
5
# 把字符串类型的json数据转换为python中的字典
str1 = '{"id": 1, "name": "tom", "tel": "17628738431"}'
data = json.loads(str1)
print(data) # {'id': 1, 'name': 'tom', 'tel': '17628738431'}
print(type(data)) # <class 'dict'>

json.dumps

把python中的对象转换为json格式的字符串

1
2
3
4
5
# 把python中的对象转换为json格式的字符串
python_data = [{"id": 1, "name": "tom", "tel": "17628738431"},{"id": 2, "name": "jerry", "tel": "17628738431"}]
str_data = json.dumps(python_data)
print(str_data) # [{"id": 1, "name": "tom", "tel": "17628738431"}, {"id": 2, "name": "jerry", "tel": "17628738431"}]
print(type(str_data)) # <class 'str'>

学生管理系统Json版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# 手敲学生管理系统
import pymysql
import json
# 这里如果写字典就会导致插入时会覆盖多条数据(不知道问什么
stu_list = []


# 定义打印菜单的方法
def menu():
print("=" * 10,end='')
print(" 学生管理系统 ", end='')
print("=" * 10)
print("\t\t 1,添加学生信息")
print("\t\t 2,修改学生信息")
print("\t\t 3,删除学生信息")
print("\t\t 4,所有学生信息")
print("\t\t 5,查询学生信息")
print("\t\t 6,退出学生系统")
print("=" * 34)


# 定义添加学生信息的方法
def add_stu():
global stu_list
stu_dict = {}
# 定义列表用于存储学生的信息
# 判断学生是否存在
sid = int(input("请输入添加学生的学号:"))
for i in stu_list:
if i['sid'] == sid:
# 说明该学生已经存在
print("该学生已经存在!")
break
else:
# 只有循环正常结束才会执行
name = input("请输入添加学生的姓名:")
age = input("请输入添加学生的年龄:")
tel = input("请输入添加学生的电话:")
# 将用户输入的内容添加到字典中
stu_dict['sid'] = sid
stu_dict['name'] = name
stu_dict['age'] = age
stu_dict['tel'] = tel
# 将字典中的值添加到列表中
stu_list.append(stu_dict)
print(stu_list)


# 修改学生信息
def modify_stu():
global stu_list
sid = int(input("请输入您要修改学生的学号:"))
# 判断该学生信息是否存在
for i in stu_list:
if i['sid'] == sid:
new_sid = int(input("请输入新的学生学号:"))
i['sid'] = new_sid
new_name = input("请输入新的学生姓名:")
i['name'] = new_name
new_age = input("请输入新的学生年龄:")
i['age'] = new_age
new_tel = input("请输入新的学生电话:")
i['tel'] = new_tel
print("修改成功!")
# cursor.execute('update stu set sid="new_sid" where sid=i["sid"]')
break
else:
# for else 只有在循环正常结束后才会执行
print("抱歉,没有这个学生!")


# 删除学生的信息
def del_stu():
sid = int(input("请输入要删除学生的学号:"))
count = 0
# 判断学生的信息是否存在
for i in stu_list:
if i['sid'] == sid:
# 执行删除(del是按照元素下标进行删除的,remove是按照元素值进行删除的
del stu_list[count]
print("删除成功!")
break
count += 1
else:
# 当循环正常结束时执行else中的语句
print("没有这个学生!")


# 所有学生的信息
def show_all():
print("学号\t姓名\t年龄\t电话\t")
for i in stu_list:
print(f"{i['sid']}\t\t{i['name']}\t{i['age']}\t{i['tel']}\t")


# 查询学生信息
def search_stu():
sid = int(input("请输入要查询学生的学号: "))
for i in stu_list:
if i.get("sid") == sid:
print("学号\t姓名\t年龄\t电话\t")
print(f"{i['sid']}\t\t{i['name']}\t{i['age']}\t{i['tel']}\t")
break
else:
print("没有查询到该学生的信息!")


# 创建判断用户录入的函数
def func():
# 打印菜单
menu()
while True:
# 使用强制类型转换,将输入的值转换为int
choice = int(input("请输入您要进行的操作:"))
# 判断用户的输入
if choice == 1:
add_stu()
elif choice == 2:
modify_stu()
elif choice == 3:
del_stu()
elif choice == 4:
show_all()
elif choice == 5:
search_stu()
elif choice == 6:
break
else:
print("没有这种操作,请您重新录入!")
continue


# 读取数据函数
def read():
global stu_list
with open("stu.json", "r", encoding="utf-8") as f:
stu_list = json.load(f)


# 写入数据函数
def write():
global stu_list
# stu_list 是列表套字典
with open("stu.json", "w", encoding="utf-8") as f:
json.dump(stu_list, f)


if __name__ == '__main__':
# 调用函数读取数据
read()
# 调用系统func函数
func()
# 调用写函数
write()