文章目录
- 前言
- [一、JSON与Python json模块简介](#一、JSON与Python json模块简介)
- 二、json模块常用方法
-
- [2.1 dumps:将 Python 对象转为 JSON 字符串](#2.1 dumps:将 Python 对象转为 JSON 字符串)
- [2.2 dump:将 Python 对象直接写入文件](#2.2 dump:将 Python 对象直接写入文件)
- [2.3 loads:将 JSON 字符串转为 Python 对象](#2.3 loads:将 JSON 字符串转为 Python 对象)
- [2.4 load:从文件类对象直接读取并转换](#2.4 load:从文件类对象直接读取并转换)
前言
本文主要介绍Python json模块简介及常用方法。
一、JSON与Python json模块简介
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,结构清晰、易于阅读和编写,能够有效提升网络传输效率。Python 内置的 json 模块提供了一系列方法,用于处理 JSON 格式数据的编码与解码。
二、json模块常用方法
json 模块主要包含 dump、dumps、load、loads 四种核心方法,用于实现 JSON 数据与 Python 对象之间的相互转换。
2.1 dumps:将 Python 对象转为 JSON 字符串
dumps() 方法可将 Python 对象转换为 JSON 格式字符串。例如,将字典转换为 JSON 字符串:
python
python
import json
data = {'id': '001', 'name': '张三', 'age': '20'}
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)
输出结果:
bash
text
{"id": "001", "name": "张三", "age": "20"}
若需格式化输出,可添加参数控制格式:
python
python
json_str = json.dumps(
data,
ensure_ascii=False,
sort_keys=True,
indent=4,
separators=(',', ': ')
)
输出结果:
bash
json
{
"age": "20",
"id": "001",
"name": "张三"
}
Python 对象与 JSON 类型对应关系
| Python | JSON |
|---|---|
| dict | object |
| list, tuple | array |
| str | string |
| int, float, 枚举类 | number |
| True | true |
| False | false |
| None | null |
将 JSON 字符串写入文件
python
python
with open('test.json', 'w', encoding='utf-8') as f:
f.write(json_str)
2.2 dump:将 Python 对象直接写入文件
dump() 方法可将 Python 对象序列化为 JSON 格式并直接写入文件类对象:
python
python
with open('test.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4, ensure_ascii=False)
该方法适用于直接将数据保存为 JSON 文件的场景。若需将数据转换为字符串(如存入数据库),则应使用 dumps()。
2.3 loads:将 JSON 字符串转为 Python 对象
loads() 方法用于将 JSON 格式字符串转换为 Python 对象:
python
python
json_str = '{"id": "001", "name": "张三", "age": "20"}'
data_dict = json.loads(json_str)
print(data_dict)
输出结果:
bash
text
{'id': '001', 'name': '张三', 'age': '20'}
JSON 类型与 Python 对象对应关系
| JSON | Python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number(int) | int |
| number (real) | float |
| true | True |
| false | False |
| null | None |
读取 JSON 文件并转换为 Python 对象
python
python
with open('test.json', encoding='utf-8') as f:
data = f.read()
print(json.loads(data))
2.4 load:从文件类对象直接读取并转换
load() 方法可直接从文件类对象中读取数据并转换为 Python 对象:
python
python
with open('test.json', encoding='utf-8') as f:
data_dict = json.load(f)
print(data_dict)
该方法与 loads() 的区别在于:load() 接收文件对象作为参数,而 loads() 接收字符串参数。