json
and file operations
1. json
Data
1. Definition
json
Bothxml
are a general-purpose data format that can be used for data exchange between different programming languages.- Contrast:
json
Relative toxml
smaller, lighter, faster transmission;xml
relative tojson
safer.
2. json
Data format
-
Require
1)一个json有且只有一个数据; 2)唯一的这个数据必须是json支持的类型的数据。
-
json
Type of support1)数字:整数、小数,直接表示:100,23.5,-3.14 2)字符串:用双引号引起来的数据:"abc"、"小明" 3)布尔:只有true和false两个值 4)null 5)相当于python的列表:[数据1,数据2,...] 6)相当于python的字典,但是键只能是字符串:{键1:值1,键2:值2,...}
-
python
Data andjson
interconversion between data1)
json
Convert to Python:json.loads
(json
format string)Note :
json
Format strings refer to strings whose contents arejson
data.json -> python 数字 -> 数字 字符串 -> 字符串(双引号变单引号) 布尔 -> 布尔(true->True, false->False) 空值 -> 空值(null->None) 数组 -> 列表 字典 -> 字典
content = open('./files/data.json', encoding='utf-8').read() result = json.loads(content) print(result) result = json.loads('"abc"') print(result, type(result)) # abc <class 'str'> result = json.loads('100') print(result, type(result)) # 100 <class 'int'> result = json.loads('true') print(result, type(result)) # True <class 'bool'>
2) Python to
json
:json.dumps
(Python data)python -> json int、float -> 数字 str -> 字符串(单引号变双引号) bool -> True->true, False->false None -> null 列表、元组 -> 数组 字典 -> 字典
result = json.dumps({ 'a': 10, 20: 30, 'name': 'xiaoming', 'isMarried': True}) print(result) # {"a": 10, "20": 30, "name": "xiaoming", "isMarried": true}
3. json
Example - adding students to the student management system
# 示例:学生管理系统添加学生
"""
数据持久化
1.已添加学生信息持久化
2.文件内容格式:json
"""
def add():
while True:
# 1.输入学生信息
print('=========添加学生==========')
name = input('请输入学生姓名:')
age = input('请输入学生年龄:')
tel = input('请输入学生电话:')
major = input('请输入学生专业:')
address = input('请输入学生籍贯:')
# 2.保存学生信息
content = open('./files/students.txt', encoding='utf-8').read()
all_students = json.loads(content)
# 添加
all_students.append({
'name': name, 'age': age, 'tel': tel, 'major': major, 'address': address})
open('./files/students.txt', 'w', encoding='utf-8').write(json.dumps(all_students))
print('添加成功!')
# 3.继续或退出
print('1.继续')
print('2.退出')
value = input('请选择:')
if value == '1':
pass
else:
# 打印所有信息
print(all_students)
break
if __name__ == '__main__':
add()
result:
=========添加学生==========
请输入学生姓名:stu4
请输入学生年龄:25
请输入学生电话:555
请输入学生专业:统计
请输入学生籍贯:福建
添加成功!
1.继续
2.退出
请选择:2
[{'name': 'stu1', 'age': '18', 'tel': '132', 'major': '信息', 'address': '四川'}, {'name': 'stu2', 'age': '119', 'tel': '118', 'major': '会计', 'address': '重庆'}, {'name': 'stu3', 'age': '21', 'tel': '124', 'major': '电子', 'address': '武汉'}, {'name': 'stu4', 'age': '25', 'tel': '555', 'major': '统计', 'address': '福建'}]