Python案例如何解析JSON数据?

wen python案例 9

本文目录导读:

Python案例如何解析JSON数据?

  1. 基础用法:解析JSON字符串
  2. 从文件读取JSON
  3. 处理复杂嵌套JSON
  4. 处理网络API返回的JSON
  5. JSON到Python类型映射
  6. 错误处理
  7. 将Python对象转换为JSON(序列化)
  8. 实用技巧

在Python中解析JSON数据非常简单,因为Python内置了json模块,下面通过几个案例详细说明。

基础用法:解析JSON字符串

import json
# JSON字符串
json_str = '{"name": "张三", "age": 25, "city": "北京"}'
# 解析JSON字符串为Python字典
data = json.loads(json_str)
print(data)  # {'name': '张三', 'age': 25, 'city': '北京'}
print(type(data))  # <class 'dict'>
print(data['name'])  # 张三

从文件读取JSON

import json
# 假设有一个 data.json 文件
# {
#     "users": [
#         {"name": "李四", "age": 30},
#         {"name": "王五", "age": 28}
#     ]
# }
# 读取并解析JSON文件
with open('data.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
# 访问数据
for user in data['users']:
    print(f"姓名: {user['name']}, 年龄: {user['age']}")

处理复杂嵌套JSON

import json
complex_json = '''
{
    "company": "ABC科技",
    "employees": [
        {
            "id": 1,
            "name": "赵六",
            "skills": ["Python", "Java", "SQL"],
            "address": {
                "city": "上海",
                "street": "南京路"
            }
        },
        {
            "id": 2,
            "name": "钱七",
            "skills": ["JavaScript", "HTML", "CSS"],
            "address": {
                "city": "北京",
                "street": "长安街"
            }
        }
    ]
}
'''
data = json.loads(complex_json)
# 遍历employees
for emp in data['employees']:
    print(f"员工: {emp['name']}")
    print(f"技能: {', '.join(emp['skills'])}")
    print(f"城市: {emp['address']['city']}")
    print("---")

处理网络API返回的JSON

import json
import requests  # 需要安装: pip install requests
# 示例:获取天气API数据
response = requests.get('https://api.example.com/weather')
weather_data = response.json()  # 直接解析为Python对象
# 或者使用json模块
weather_data = json.loads(response.text)
print(f"温度: {weather_data['main']['temp']}°C")
print(f"湿度: {weather_data['main']['humidity']}%")

JSON到Python类型映射

JSON Python
object dict
array list
string str
number (int) int
number (float) float
true True
false False
null None
import json
json_data = '''
{
    "string": "hello",
    "integer": 42,
    "float": 3.14,
    "boolean_true": true,
    "boolean_false": false,
    "null_value": null,
    "array": [1, 2, 3],
    "nested": {"key": "value"}
}
'''
parsed = json.loads(json_data)
print(parsed['string'])  # hello
print(parsed['integer'])  # 42
print(parsed['boolean_true'])  # True
print(parsed['null_value'])  # None

错误处理

import json
invalid_json = '{"name": "张三", age: 25}'  # 缺少引号
try:
    data = json.loads(invalid_json)
except json.JSONDecodeError as e:
    print(f"JSON解析错误: {e}")
    print(f"错误位置: 第{e.lineno}行, 第{e.colno}列")

将Python对象转换为JSON(序列化)

import json
# Python字典
data = {
    "name": "小明",
    "age": 20,
    "languages": ["Python", "JavaScript"],
    "is_student": True
}
# 转换为JSON字符串
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# 写入文件
with open('output.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

实用技巧

import json
# 1. 格式化JSON输出
print(json.dumps(data, indent=2, sort_keys=True))
# 2. 处理中文
print(json.dumps(data, ensure_ascii=False))  # 显示中文而不是Unicode转义
# 3. 自定义对象序列化
from datetime import datetime
class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)
data = {
    "timestamp": datetime.now()
}
json_str = json.dumps(data, cls=CustomEncoder)
print(json_str)
  • json.loads(): 解析JSON字符串
  • json.load(): 从文件读取JSON
  • json.dumps(): Python对象转JSON字符串
  • json.dump(): Python对象写入JSON文件
  • 始终使用try-except处理可能的JSON解析错误
  • 处理中文时设置ensure_ascii=False

这些是Python中处理JSON最常用的方法,掌握了这些就足以应对大多数JSON解析场景。

抱歉,评论功能暂时关闭!