当前位置:首页>python>Python json 模块 超详细精讲

Python json 模块 超详细精讲

  • 2026-10-11 07:50:38
Python json 模块 超详细精讲

dumps / loads / dump / load

(最核心、最常用、面试必考)


一、json 是什么

  • • JSON = 轻量级文本数据格式
  • • 用于:数据传输、存文件、接口交互
  • • Python ↔ JSON 互相转换

二、4 个核心函数(必背)

函数
作用
json.dumps()
Python 对象 → JSON 字符串
json.loads()
JSON 字符串 → Python 对象
json.dump()
Python 对象 → 写入 JSON 文件
json.load()
读取 JSON 文件 → Python 对象

1. json.dumps()

Python 数据 → JSON 字符串

import jsondata = {"name": "小明","age": 18,"gender": True}# 转 JSON 字符串json_str = json.dumps(data, ensure_ascii=False, indent=4)print(json_str)

常用参数

  • • ensure_ascii=False:正常显示中文
  • • indent=4:格式化缩进,好看

2. json.loads()

JSON 字符串 → Python 数据

json_str = '''{"name":"小明","age":18,"gender":true}'''# 转回字典data = json.loads(json_str)print(data["name"])

3. json.dump()

Python 数据 → 写入 JSON 文件

data = {"name": "小红", "age": 20}withopen("data.json", "w", encoding="utf-8") as f:    json.dump(data, f, ensure_ascii=False, indent=4)

4. json.load()

读取 JSON 文件 → Python 数据

withopen("data.json", "r", encoding="utf-8") as f:    data = json.load(f)print(data)

三、Python ↔ JSON 类型对应表

Python
JSON
dict
object
list, tuple
array
str
string
int, float
number
True
true
False
false
None
null

四、超级记忆口诀(必背)

  • • 带 s = 字符串操作
    • • dumps → 转字符串
    • • loads ← 读字符串
  • • 不带 s = 文件操作
    • • dump → 写入文件
    • • load ← 读取文件

五、完整小案例(最常用)

import json# 1. 字典 → JSON 字符串data = {"name": "张三", "score": 90}s = json.dumps(data, ensure_ascii=False, indent=2)# 2. JSON 字符串 → 字典new_data = json.loads(s)# 3. 字典 → 写入文件withopen("user.json", "w", encoding="utf-8") as f:    json.dump(new_data, f, ensure_ascii=False, indent=2)# 4. 读取文件 → 字典withopen("user.json", encoding="utf-8") as f:    res = json.load(f)

📌 一句话总结

  • • dumps/loads:内存里转字符串
  • • dump/load:和文件打交道

最新文章

随机文章