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(键排序)
相关推荐
m0_6070766010 小时前
CSS3 转换,快手前端面试经验,隔壁都馋哭了
前端·面试·css3
青云计划11 小时前
知光项目知文发布模块
java·后端·spring·mybatis
Victor35611 小时前
MongoDB(9)什么是MongoDB的副本集(Replica Set)?
后端
NEXT0611 小时前
二叉搜索树(BST)
前端·数据结构·面试
Victor35611 小时前
MongoDB(8)什么是聚合(Aggregation)?
后端
NEXT0611 小时前
JavaScript进阶:深度剖析函数柯里化及其在面试中的底层逻辑
前端·javascript·面试
yeyeye11113 小时前
Spring Cloud Data Flow 简介
后端·spring·spring cloud
Tony Bai13 小时前
告别 Flaky Tests:Go 官方拟引入 testing/nettest,重塑内存网络测试标准
开发语言·网络·后端·golang·php
+VX:Fegn089513 小时前
计算机毕业设计|基于springboot + vue鲜花商城系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
程序猿阿伟14 小时前
《GraphQL批处理与全局缓存共享的底层逻辑》
后端·缓存·graphql