Python学习(5) ----- Python的JSON处理

下面是关于 Python 中如何全面处理 JSON 的详细说明,包括模块介绍、数据类型映射、常用函数、文件操作、异常处理、进阶技巧等。


一、什么是 JSON?

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于 API 和配置文件。

示例:

{
  "name": "张三",
  "age": 28,
  "is_student": false,
  "skills": ["Python", "Java"],
  "address": {
    "city": "北京",
    "zipcode": "100000"
  }
}

️ 二、Python json 模块简介

Python 提供内置模块 json,支持 JSON 和 Python 对象之间的 序列化(encode)反序列化(decode)

import json

三、JSON 与 Python 数据类型映射表

JSON 类型 Python 类型
object dict
array list
string str
number int / float
true / false True / False
null None

✍️ 四、常用函数详细说明

1. json.dumps() — Python 对象 → JSON 字符串

import json

data = {"name": "李雷", "age": 20}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)

参数说明

  • ensure_ascii=False:中文不转义,默认是 True(会变成 \uXXXX)
  • indent=2:格式化输出,2 表示缩进空格数
  • sort_keys=True:按键名排序输出

2. json.loads() — JSON 字符串 → Python 对象

json_str = '{"name": "韩梅梅", "age": 22}'
data = json.loads(json_str)
print(data["name"])  # 韩梅梅

3. json.dump() — Python 对象 → 写入 JSON 文件

data = {"name": "Tom", "age": 18}
with open("user.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

4. json.load() — 从 JSON 文件读取为 Python 对象

with open("user.json", "r", encoding="utf-8") as f:
    data = json.load(f)
print(data["name"])

五、异常处理

处理不合法 JSON 字符串时要加异常保护:

try:
    json_str = '{"name": "Error", "age": 30'  # 缺少结尾大括号
    data = json.loads(json_str)
except json.JSONDecodeError as e:
    print("JSON 解析失败:", e)

六、复杂嵌套结构处理

json_str = '''
{
  "user": {
    "name": "张三",
    "info": {
      "age": 30,
      "skills": ["Python", "Go"]
    }
  }
}
'''

data = json.loads(json_str)
print(data["user"]["info"]["skills"][0])  # Python

七、技巧 & 补充

1. 将 Python 类对象转为 JSON(需要先转字典)

class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

u = User("Lucy", 18)
json_str = json.dumps(u.__dict__, ensure_ascii=False)
print(json_str)

2. 处理含中文的 JSON 文件

务必加上 encoding='utf-8',否则可能乱码。


八、实际应用场景举例

示例:修改 JSON 文件中的某个字段

with open("config.json", "r", encoding="utf-8") as f:
    config = json.load(f)

config["debug"] = False

with open("config.json", "w", encoding="utf-8") as f:
    json.dump(config, f, ensure_ascii=False, indent=2)

如果你有:

  • 一个具体的 JSON 文件想修改字段
  • 某种嵌套结构想提取信息
  • 想把 Python 数据存成 JSON 数据库
    都可以发给我,我可以写具体的例子帮你。

你可能感兴趣的:(Python,python,学习,json)