跳到主要内容

🧠 Python 标准库 - json 模块详解(JSON 数据处理)

json 模块用于在 Python 与 JSON(JavaScript Object Notation)格式之间进行转换,是常用的数据交换格式。


🔄 一、Python 对象转 JSON 字符串(序列化)

import json

数据 = {
"name": "小明",
"age": 20,
"is_student": True,
"scores": [90, 88, 92]
}

json字符串 = json.dumps(数据, ensure_ascii=False)
打印(json字符串) # 输出:{"name": "小明", "age": 20, "is_student": true, "scores": [90, 88, 92]}

📥 二、JSON 字符串转 Python 对象(反序列化)

import json

json字符串 = '{"name": "小红", "age": 22, "is_student": false, "scores": [95, 90, 85]}'

数据 = json.loads(json字符串)
打印(数据)
打印(数据["name"]) # 输出:小红

💾 三、JSON 文件读写

写入 JSON 文件

import json

数据 = {
"city": "北京",
"population": 21540000
}

with open("data.json", "w", encoding="utf-8") as 文件:
json.dump(数据, 文件, ensure_ascii=False)

读取 JSON 文件

import json

with open("data.json", "r", encoding="utf-8") as 文件:
数据 = json.load(文件)

打印(数据)

📘 常用函数概览

函数功能
json.dumps(obj, ...)将 Python 对象序列化为 JSON 字符串
json.loads(s, ...)将 JSON 字符串反序列化为 Python 对象
json.dump(obj, file, ...)将 Python 对象写入 JSON 文件
json.load(file, ...)从 JSON 文件读取 Python 对象