当前位置: 首页 > news >正文

Python 中将 JSON 字符串转为对象的几种方法对比

在 Python 中,将 JSON 字符串转换为对象有多种方式,下面详细介绍最常用的几种方法:

1. 使用 json.loads() 转换为字典

这是最基本的方法,将 JSON 字符串转换为 Python 字典。

python

import json# JSON 字符串
json_str = '{"name": "张三", "age": 25, "is_student": false, "hobbies": ["篮球", "阅读"]}'# 转换为字典
data_dict = json.loads(json_str)
print(type(data_dict))  # <class 'dict'>
print(data_dict)
# {'name': '张三', 'age': 25, 'is_student': False, 'hobbies': ['篮球', '阅读']}# 访问数据
print(data_dict['name'])      # 张三
print(data_dict['hobbies'][0]) # 篮球

2. 转换为自定义对象

方法一:手动创建对象

python

import jsonclass Person:def __init__(self, name, age, is_student, hobbies):self.name = nameself.age = ageself.is_student = is_studentself.hobbies = hobbiesdef __str__(self):return f"Person(name={self.name}, age={self.age}, is_student={self.is_student})"# JSON 字符串
json_str = '{"name": "李四", "age": 30, "is_student": true, "hobbies": ["音乐", "旅行"]}'# 先转换为字典
data_dict = json.loads(json_str)# 手动创建对象
person = Person(name=data_dict['name'],age=data_dict['age'],is_student=data_dict['is_student'],hobbies=data_dict['hobbies']
)print(person)  # Person(name=李四, age=30, is_student=True)
print(person.hobbies)  # ['音乐', '旅行']

方法二:使用 object_hook 参数(推荐)

python

import jsonclass Person:def __init__(self, name, age, is_student, hobbies):self.name = nameself.age = ageself.is_student = is_studentself.hobbies = hobbiesdef __str__(self):return f"Person(name={self.name}, age={self.age})"def dict_to_person(dct):"""将字典转换为 Person 对象的钩子函数"""return Person(name=dct.get('name'),age=dct.get('age'),is_student=dct.get('is_student', False),hobbies=dct.get('hobbies', []))# JSON 字符串
json_str = '{"name": "王五", "age": 22, "is_student": true, "hobbies": ["编程", "游戏"]}'# 直接转换为对象
person = json.loads(json_str, object_hook=dict_to_person)
print(type(person))  # <class '__main__.Person'>
print(person)        # Person(name=王五, age=22)
print(person.hobbies)  # ['编程', '游戏']

方法三:使用 dataclasses (Python 3.7+)

python

import json
from dataclasses import dataclass
from typing import List@dataclass
class Person:name: strage: intis_student: bool = Falsehobbies: List[str] = Nonedef __post_init__(self):if self.hobbies is None:self.hobbies = []# JSON 字符串
json_str = '{"name": "赵六", "age": 28, "is_student": false, "hobbies": ["烹饪", "电影"]}'# 转换为字典后创建对象
data_dict = json.loads(json_str)
person = Person(**data_dict)print(person)  # Person(name='赵六', age=28, is_student=False, hobbies=['烹饪', '电影'])

3. 处理嵌套 JSON 对象

python

import jsonclass Address:def __init__(self, city, street):self.city = cityself.street = streetdef __str__(self):return f"{self.city}市{self.street}"class User:def __init__(self, name, age, address):self.name = nameself.age = ageself.address = addressdef __str__(self):return f"User(name={self.name}, age={self.age}, address={self.address})"def complex_dict_to_obj(dct):"""处理嵌套对象的转换"""if 'city' in dct and 'street' in dct:return Address(dct['city'], dct['street'])elif 'name' in dct and 'age' in dct and 'address' in dct:return User(dct['name'], dct['age'], dct['address'])return dct# 嵌套 JSON 字符串
json_str = '''
{"name": "钱七","age": 35,"address": {"city": "北京","street": "朝阳区建国路"}
}
'''user = json.loads(json_str, object_hook=complex_dict_to_obj)
print(user)  # User(name=钱七, age=35, address=北京市朝阳区建国路)

4. 使用第三方库 marshmallow

对于复杂的 JSON 转换,推荐使用 marshmallow 库:

python

# 首先安装: pip install marshmallow
from marshmallow import Schema, fields, post_loadclass PersonSchema(Schema):name = fields.Str()age = fields.Int()is_student = fields.Bool()hobbies = fields.List(fields.Str())@post_loaddef make_person(self, data, **kwargs):return Person(**data)# JSON 字符串
json_str = '{"name": "孙八", "age": 26, "is_student": true, "hobbies": ["游泳", "摄影"]}'# 使用 schema 转换
schema = PersonSchema()
person = schema.loads(json_str)print(type(person))  # <class '__main__.Person'>
print(person)        # Person(name=孙八, age=26, is_student=True)

5. 处理 JSON 数组

python

import jsonclass Product:def __init__(self, name, price):self.name = nameself.price = pricedef __str__(self):return f"Product(name={self.name}, price=¥{self.price})"def dict_to_product(dct):if 'name' in dct and 'price' in dct:return Product(dct['name'], dct['price'])return dct# JSON 数组字符串
json_array_str = '''
[{"name": "笔记本电脑", "price": 5999},{"name": "智能手机", "price": 3999},{"name": "耳机", "price": 299}
]
'''products = json.loads(json_array_str, object_hook=dict_to_product)
for product in products:print(product)
# Product(name=笔记本电脑, price=¥5999)
# Product(name=智能手机, price=¥3999)
# Product(name=耳机, price=¥299)

总结

方法优点缺点适用场景
json.loads()简单直接返回字典,不是对象快速访问数据
object_hook灵活,支持自定义转换需要手动编写转换逻辑复杂对象转换
dataclasses代码简洁,类型安全需要 Python 3.7+数据类对象
marshmallow功能强大,验证数据需要安装第三方库生产环境,复杂需求

根据你的具体需求选择合适的方法。对于简单的数据访问,使用字典即可;对于需要面向对象编程的场景,推荐使用 object_hook 或 dataclasses

http://www.dtcms.com/a/363935.html

相关文章:

  • (五)Python控制结构(循环结构)
  • 最快的 C 语言 JSON 库 - yyjson
  • 爬虫-----最全的爬虫库介绍(一篇文章让你成为爬虫大佬,爬你想爬)
  • 【鸿蒙心迹】从疑惑到热爱:我的鸿蒙开发启蒙
  • Java消息中间件(RocketMQ)
  • Linux 文本处理实战手册
  • 【专栏升级】大模型应用实战并收录RAG专题,Agent专题,LLM重构数据科学流程专题,端侧AI专题,累计63篇文章
  • Redis 哨兵 (基于 Docker)
  • YOLO 目标检测:YOLOv5网络结构、Focus、CSP、自适应Anchor、激活函数SiLU、SPPF、C3
  • 3.2-C++基础组件
  • Kafka面试精讲 Day 5:Broker集群管理与协调机制
  • 深度学习-----通过本地数据实现图片识别的训练
  • PS痕迹检测器:基于深度学习的图像篡改检测
  • 撤销修改 情况⼀:对于⼯作区的代码,还没有 add
  • 浏览器内存 (JavaScript运行时内存)存储的优劣分析
  • linux(cut,sort,uniq ,tr,sed,awk)命令介绍
  • 贝叶斯定理:理解概率更新与实际场景应用
  • 在VS Code中直接操控浏览器
  • 预算紧张?这5款低代码平台免费还好用!
  • 光储充一体化智慧能源平台助力某能投公司绿色能源转型
  • 【面试场景题】如何理解设计模式
  • three.js手机端的4种旋转方式
  • 有鹿巡扫机器人:智慧清洁时代的多面手
  • (四)Python控制结构(条件结构)
  • MMORPG 游戏战斗系统架构
  • 2025互联网大厂Java后端面试:3-5年经验必问核心考点解析
  • 机器学习辅助的Backtrader资产配置优化策略
  • 【vue2】vue2.7x的项目中集成tailwind.css真的不要太香
  • Python 类的方法类型详解
  • 企业如何实现零工用工零风险?盖雅全自动化合规管控