Python编程基础:快速了解JSON和Python的对应关系

Python的json库是处理JSON数据的利器,它能轻松地在Python数据和JSON格式之间转换。

快速了解JSON和Python的对应关系

首先记住这个核心对应表,这是理解后续操作的基础:

JSON 类型 Python 类型
对象 {} 字典 dict
数组 [] 列表 list
字符串 " " 字符串 str
数字 123 整数 int/浮点数 float
布尔值 true/false 布尔值 True/False
null None

基础操作:编码与解码

1. 将Python对象转为JSON字符串(编码)

Python 复制代码
import json

# Python字典
data = {
    "name": "张三",
    "age": 25,
    "is_student": True,
    "hobbies": ["阅读", "游泳", "编程"],
    "address": {
        "city": "北京",
        "postcode": "100000"
    }
}

# 转换为JSON字符串
json_string = json.dumps(data, ensure_ascii=False, indent=2)
print("JSON字符串:")
print(json_string)

输出结果:

json 复制代码
{
  "name": "张三",
  "age": 25,
  "is_student": true,
  "hobbies": [
    "阅读",
    "游泳",
    "编程"
  ],
  "address": {
    "city": "北京",
    "postcode": "100000"
  }
}

2. 将JSON字符串转为Python对象(解码)

Python 复制代码
# JSON字符串
json_str = '''{
    "product": "笔记本电脑",
    "price": 5999.99,
    "in_stock": true,
    "specs": ["i7处理器", "16GB内存", "512GB SSD"]
}'''

# 转换为Python字典
python_dict = json.loads(json_str)
print("Python字典:")
print(python_dict)
print(f"商品名称: {python_dict['product']}")
print(f"价格: {python_dict['price']}元")
print(f"规格: {', '.join(python_dict['specs'])}")

输出结果:

Python 复制代码
Python字典:
{'product': '笔记本电脑', 'price': 5999.99, 'in_stock': True, 'specs': ['i7处理器', '16GB内存', '512GB SSD']}
商品名称: 笔记本电脑
价格: 5999.99元
规格: i7处理器, 16GB内存, 512GB SSD

文件读写操作

3. 将数据保存到JSON文件

Python 复制代码
import json

# 要保存的数据
users = [
    {"id": 1, "name": "李小明", "email": "li@example.com"},
    {"id": 2, "name": "王小红", "email": "wang@example.com"},
    {"id": 3, "name": "赵小刚", "email": "zhao@example.com"}
]

# 写入JSON文件
with open('users.json', 'w', encoding='utf-8') as file:
    json.dump(users, file, ensure_ascii=False, indent=2)

print("数据已保存到 users.json 文件")

4. 从JSON文件读取数据

Python 复制代码
# 从文件读取JSON数据
with open('users.json', 'r', encoding='utf-8') as file:
    loaded_users = json.load(file)

print("从文件读取的用户数据:")
for user in loaded_users:
    print(f"ID: {user['id']}, 姓名: {user['name']}, 邮箱: {user['email']}")

处理特殊数据类型

5. 处理日期时间对象

Python 复制代码
import json
from datetime import datetime

def custom_serializer(obj):
    """自定义序列化函数"""
    if isinstance(obj, datetime):
        return obj.isoformat()  # 转换为ISO格式字符串
    raise TypeError(f"类型 {type(obj)} 不可序列化")

# 包含日期时间的数据
event = {
    "title": "项目会议",
    "time": datetime.now(),
    "participants": ["张三", "李四"]
}

# 使用自定义序列化
json_output = json.dumps(event, default=custom_serializer, ensure_ascii=False, indent=2)
print("包含日期时间的数据:")
print(json_output)

实际应用案例

6. 处理API返回的JSON数据

Python 复制代码
import json

# 模拟API返回的JSON数据
api_response = '''
{
    "status": "success",
    "data": {
        "weather": {
            "city": "上海",
            "temperature": 28,
            "conditions": "晴",
            "humidity": 65
        }
    },
    "timestamp": "2025-07-20T14:30:00"
}
'''

# 解析API数据
response_data = json.loads(api_response)

if response_data["status"] == "success":
    weather = response_data["data"]["weather"]
    print(f"城市: {weather['city']}")
    print(f"温度: {weather['temperature']}°C")
    print(f"天气: {weather['conditions']}")
    print(f"湿度: {weather['humidity']}%")
else:
    print("API请求失败")

7. 配置文件的读写

Python 复制代码
import json
import os

def update_config(setting_name, new_value):
    """更新配置文件"""
    
    # 如果配置文件不存在,创建默认配置
    if not os.path.exists('config.json'):
        default_config = {
            "language": "zh-CN",
            "theme": "dark",
            "notifications": True,
            "font_size": 14
        }
        with open('config.json', 'w', encoding='utf-8') as file:
            json.dump(default_config, file, ensure_ascii=False, indent=2)
    
    # 读取现有配置
    with open('config.json', 'r', encoding='utf-8') as file:
        config = json.load(file)
    
    # 更新配置
    config[setting_name] = new_value
    
    # 保存更新后的配置
    with open('config.json', 'w', encoding='utf-8') as file:
        json.dump(config, file, ensure_ascii=False, indent=2)
    
    print(f"配置已更新: {setting_name} = {new_value}")

# 使用示例
update_config("theme", "light")
update_config("font_size", 16)

实用技巧和注意事项

格式化输出选项

Python 复制代码
data = {"name": "Alice", "age": 30, "city": "New York"}

# 紧凑格式(默认)
compact = json.dumps(data)
print("紧凑格式:", compact)

# 美化格式(缩进2个空格)
pretty = json.dumps(data, indent=2)
print("美化格式:")
print(pretty)

# 按键排序
sorted_output = json.dumps(data, indent=2, sort_keys=True)
print("按键排序:")
print(sorted_output)

错误处理

Python 复制代码
import json

def safe_json_parse(json_str):
    """安全的JSON解析函数"""
    try:
        data = json.loads(json_str)
        return data
    except json.JSONDecodeError as e:
        print(f"JSON解析错误: {e}")
        return None

# 测试错误处理
invalid_json = '{"name": "Alice", "age": 30,}'  # 尾部多余的逗号
result = safe_json_parse(invalid_json)

if result is None:
    print("成功处理了无效的JSON输入")

总结

通过以上案例,你已经掌握了json库的核心功能:

  • 编码json.dumps()(转字符串)和 json.dump()(写文件)
  • 解码json.loads()(转字典)和 json.load()(读文件)
  • 重要参数ensure_ascii=False(支持中文)、indent(格式化)、sort_keys=True(键排序)
相关推荐
名字还没想好☜23 分钟前
Go 的 io.Reader/Writer 组合实战:io.Copy、TeeReader、MultiWriter 优雅处理数据流
开发语言·后端·golang·go·iphone
喵个咪1 小时前
GoWind Shop 架构剖析:一个 REST 请求穿越三服务 BFF 的七环链路
vue.js·后端·go
喵个咪1 小时前
GoWind Shop 安全设计:JWT 鉴权、Ent 行级隔离、防篡改审计与四个真实漏洞修复
vue.js·后端·go
喵个咪1 小时前
GoWind Shop:一个 proto 文件如何生成后端、前端、文档、校验六路代码
vue.js·后端·go
用户7783366132111 小时前
从 0 搭一个关键词排名监控:核心思路 + 可运行代码
后端·python·api
喵个咪1 小时前
GoWind Shop 出海实战:多语言商品内容怎么存、怎么录、怎么按 locale 取
vue.js·后端·go
Tsuki_tl1 小时前
【面试高频】 HashMap, HashTable,ConcurrentHashMap 之间的区别
面试·hashmap·synchronized·哈希表·多线程并发·hashtable·分段锁
城管不管2 小时前
第八次面试2026.8.10
面试·职场和发展
郝学胜_神的一滴2 小时前
C++20 高级编程 001:从极简HelloWorld到现代类型体系全梳理
c++·后端
卷无止境2 小时前
FastAPI中间件全解析:请求处理链条上的隐形关卡
后端·python·fastapi