You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何将含对象列表的自定义类对象序列化为JSON

自定义类包含对象列表时的JSON序列化实现方案

运行序列化代码时抛出如下错误:

TypeError: Object of type person is not JSON serializable


问题复现代码

import json

class person:
    def __init__(self, name, cars):
        self._name = name
        self._cars = cars
    
class car:
    def __init__(self, brand, color):
        self._brand = brand
        self._color = color

Jason = person("Jason", [car("Toyota", "Blue"), car("Honda", "Red")])

json = json.dumps(Jason)
print(json)

期望输出格式

{
    "name": "Jason",
    "cars":[
        {
            "brand": "Toyota",
            "color": "Blue"
        },
        {
            "brand": "Honda",
            "color": "Red"
        }
    ]
}

报错原因

Python标准库json模块默认仅支持序列化字典、列表、字符串、数字、布尔值、None这类原生数据类型,无法直接识别自定义类的实例对象,因此抛出类型错误。

可行实现方案

以下两种方案均可正常运行,输出符合预期结构的JSON内容:

  • 方案1:传入default参数自定义序列化逻辑
    利用json.dumps的default参数,指定遇到非原生类型时的转换规则,无需手动逐层转换嵌套对象:

    import json
    
    class person:
        def __init__(self, name, cars):
            self._name = name
            self._cars = cars
        
    class car:
        def __init__(self, brand, color):
            self._brand = brand
            self._color = color
    
    def serialize_custom(obj):
        if isinstance(obj, person):
            return {"name": obj._name, "cars": obj._cars}
        if isinstance(obj, car):
            return {"brand": obj._brand, "color": obj._color}
        raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
    
    Jason = person("Jason", [car("Toyota", "Blue"), car("Honda", "Red")])
    # indent=4用于格式化输出,匹配预期的缩进结构
    result = json.dumps(Jason, default=serialize_custom, indent=4)
    print(result)
    
  • 方案2:给自定义类添加字典转换方法
    如果类需要频繁序列化,可以在类内部实现转字典的方法,序列化时直接调用方法得到原生字典结构再转JSON:

    import json
    
    class person:
        def __init__(self, name, cars):
            self._name = name
            self._cars = cars
        def to_dict(self):
            return {
                "name": self._name,
                "cars": [car_item.to_dict() for car_item in self._cars]
            }
        
    class car:
        def __init__(self, brand, color):
            self._brand = brand
            self._color = color
        def to_dict(self):
            return {"brand": self._brand, "color": self._color}
    
    Jason = person("Jason", [car("Toyota", "Blue"), car("Honda", "Red")])
    result = json.dumps(Jason.to_dict(), indent=4)
    print(result)
    

内容的提问来源于stack exchange,提问作者Olivier Coujan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 10:57:54