目录
- Python快速上手(二十四)
- Python3 JSON数据解析
- 编码(序列化)
- 解码(反序列化)
- 读写JSON文件
Python快速上手(二十四)
Python3 JSON数据解析
在Python 3中,使用JSON(JavaScript Object Notation)是一种方便的方式来处理和交换数据。JSON是一种轻量级的数据交换格式,易于阅读和编写,常用于Web应用程序和API之间的数据交换。Python 3中提供了内置的json模块,用于处理JSON数据的编码(序列化)和解码(反序列化)。
Python 编码为 JSON 类型转换对应表:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
JSON 解码为 Python 类型转换对应表:
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
编码(序列化)
编码是将Python对象转换为JSON格式的过程。json模块提供了json.dumps()方法来将Python对象编码为JSON字符串。
import json# Python对象
data = {'name': 'Alice','age': 30,'is_student': False,'courses': ['Math', 'Science']
}# 编码为JSON字符串
json_string = json.dumps(data)
print(json_string)
在上面的示例中,我们定义了一个Python字典data,然后使用json.dumps()方法将其编码为JSON字符串。输出结果将是一个符合JSON格式的字符串。
解码(反序列化)
解码是将JSON格式的数据转换为Python对象的过程。json模块提供了json.loads()方法来将JSON字符串解码为Python对象。
import json# JSON字符串
json_string = '{"name": "Bob", "age": 25, "is_student": true, "courses": ["History", "English"]}'# 解码为Python对象
data = json.loads(json_string)
print(data)
在上面的示例中,我们定义了一个JSON格式的字符串json_string,然后使用json.loads()方法将其解码为Python对象。输出结果将是一个Python字典。
读写JSON文件
除了编码和解码JSON数据,json模块还提供了方便的方法来读写JSON文件。
import json# 写入JSON文件
data = {'name': 'Charlie','age': 35,'is_student': True,'courses': ['Art', 'Music']
}with open('data.json', 'w') as file:json.dump(data, file)# 读取JSON文件
with open('data.json', 'r') as file:data = json.load(file)print(data)
在上面的示例中,我们使用json.dump()方法将Python对象写入到JSON文件中,然后使用json.load()方法从JSON文件中读取数据并转换为Python对象。