1.1 基础知识
- 什么是JSON:(JavaScript Object Notation)是一种简洁、易读的数据语言,广泛用于数据交换、文档储存和web开发;适合数据量大,不要求保留原有的数据类型。
- 导入:import json,这是最基础的文件操作库。
1.2 JSON语法的语法
①基本结构:
- JSON由键值对组成,每个键对应1个或多个值;
- 使用双引号括起键和值,其中键是字符串,值可以是任何合法的javascript表达式。
- 例1(字典Dictionary):
- 例2:列表(List):
1.3 JSON文件的读写
- 案例1:将Python的字典储存到JSON文件中,可以使用json.dump()函数来完成。
import json
# 定义包含多个对象的字典列表
data = [
{"name": "Alice", "age": 25, "city": "Beijing"},
{"name": "Bob", "age": 30, "city": "Shanghai"},
{"name": "Charlie", "age": 28, "city": "Guangzhou"}
]
# 将列表写入 JSON 文件
with open("data.json", "w", encoding="utf-8") as file:
json.dump(data, file, ensure_ascii=False, indent=4)
print("数据已成功写入 data.json 文件")
print(json.dumps(data))
- 案例2:读取 JSON 文件并加载为 Python 对象。
with open("data.json", "r", encoding="utf-8") as file:
loaded_data = json.load(file)
print(loaded_data) #读取文件中json形式的字符串元素转化为Python类型