百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

Python开发必备:自定义JSON编码器完全指南

wptr33 2025-07-08 23:40 9 浏览

在现代软件开发中,数据序列化是一个至关重要的技术环节,它负责将复杂的程序对象转换为可传输和存储的格式。JSON作为最广泛使用的数据交换格式,在Web服务、API接口和数据持久化中发挥着核心作用。然而,Python标准库中的JSON模块仅支持基本数据类型的序列化,面对复杂的自定义对象时往往力不从心。

基本原理与挑战

JSON序列化本质上是一个将内存中的对象表示转换为字符串格式的过程。Python的标准json模块基于递归下降的方式处理数据结构,它能够自动识别并序列化字典、列表、字符串、数字、布尔值和None等基本类型。这种机制的核心在于类型检测和格式转换,通过遍历对象的内部结构来生成对应的JSON表示。

当面对自定义类实例、日期时间对象、集合类型或其他复杂数据结构时,标准JSON模块会抛出TypeError异常。这是因为JSON规范本身只定义了有限的数据类型,无法直接表示Python中丰富的对象类型。解决这一挑战的关键在于建立对象到JSON表示的映射关系,将复杂对象的内部状态提取出来,转换为JSON支持的基本类型。

自定义编码器实现

实现自定义JSON编码器的核心方法是继承json.JSONEncoder类并重写其default方法。这个方法在遇到无法序列化的对象时被调用,可以提供自定义的序列化逻辑。

下面的实现展示了一个完整的自定义编码器,能够处理日期时间对象、集合类型、自定义类实例等多种复杂情况。

import json
import datetime
from decimal import Decimal
from dataclasses import dataclass

class CustomJSONEncoder(json.JSONEncoder):
    """
    自定义JSON编码器,支持多种复杂数据类型的序列化
    处理日期时间、集合、自定义对象等类型
    """
    
    def default(self, obj):
        # 处理日期时间对象
        if isinstance(obj, datetime.datetime):
            return {
                '__type__': 'datetime',
                'value': obj.isoformat()
            }
        
        if isinstance(obj, datetime.date):
            return {
                '__type__': 'date',
                'value': obj.isoformat()
            }
        
        # 处理集合类型
        if isinstance(obj, set):
            return {
                '__type__': 'set',
                'value': list(obj)
            }
        
        if isinstance(obj, tuple):
            return {
                '__type__': 'tuple',
                'value': list(obj)
            }
        
        # 处理Decimal类型
        if isinstance(obj, Decimal):
            return {
                '__type__': 'decimal',
                'value': str(obj)
            }
        
        # 处理自定义对象
        if hasattr(obj, '__dict__'):
            return {
                '__type__': 'custom_object',
                '__class__': obj.__class__.__name__,
                'attributes': obj.__dict__
            }
        
        # 处理dataclass对象
        if hasattr(obj, '__dataclass_fields__'):
            return {
                '__type__': 'dataclass',
                '__class__': obj.__class__.__name__,
                'fields': {field.name: getattr(obj, field.name) 
                          for field in obj.__dataclass_fields__.values()}
            }
        
        return super().default(obj)

# 定义测试类
@dataclass
class Person:
    name: str
    age: int
    email: str

class Product:
    def __init__(self, name, price, tags):
        self.name = name
        self.price = price
        self.tags = tags
        self.created_at = datetime.datetime.now()

# 创建测试数据
test_data = {
    'person': Person('张三', 30, 'zhangsan@example.com'),
    'product': Product('智能手机', Decimal('2999.99'), {'电子产品', '通讯设备'}),
    'timestamp': datetime.datetime.now(),
    'numbers': (1, 2, 3, 4, 5)
}

# 使用自定义编码器进行序列化
json_string = json.dumps(test_data, cls=CustomJSONEncoder, indent=2, ensure_ascii=False)
print("序列化结果:")
print(json_string)

运行结果:

序列化结果:
{
  "person": {
    "__type__": "custom_object",
    "__class__": "Person",
    "attributes": {
      "name": "张三",
      "age": 30,
      "email": "zhangsan@example.com"
    }
  },
  "product": {
    "__type__": "custom_object",
    "__class__": "Product",
    "attributes": {
      "name": "智能手机",
      "price": {
        "__type__": "decimal",
        "value": "2999.99"
      },
      "tags": {
        "__type__": "set",
        "value": [
          "电子产品",
          "通讯设备"
        ]
      },
      "created_at": {
        "__type__": "datetime",
        "value": "2025-06-08T12:59:16.355264"
      }
    }
  },
  "timestamp": {
    "__type__": "datetime",
    "value": "2025-06-08T12:59:16.355270"
  },
  "numbers": [
    1,
    2,
    3,
    4,
    5
  ]
}

高级编码器

为了构建更加强大的序列化系统,需要实现循环引用检测、深度限制和选择性序列化等高级功能。

下面的实现展示了一个功能完整的高级编码器,提供了生产环境所需的各种特性。

import datetime
import json


class AdvancedJSONEncoder(json.JSONEncoder):
    """
    高级JSON编码器,支持循环引用检测、深度限制等功能
    """

    def __init__(self, *args, **kwargs):
        self.max_depth = kwargs.pop('max_depth', 10)
        self.skip_private = kwargs.pop('skip_private', True)
        super().__init__(*args, **kwargs)
        self._obj_tracker = set()
        self._current_depth = 0

    def encode(self, obj):
        self._obj_tracker.clear()
        self._current_depth = 0
        return super().encode(obj)

    def default(self, obj):
        # 深度检查
        if self._current_depth > self.max_depth:
            return f"<深度超限>"

        # 循环引用检查
        obj_id = id(obj)
        if obj_id in self._obj_tracker:
            return f"<循环引用: {type(obj).__name__}>"

        self._obj_tracker.add(obj_id)
        self._current_depth += 1

        try:
            # 处理日期时间
            if isinstance(obj, datetime.datetime):
                return {'__type__': 'datetime', 'value': obj.isoformat()}

            # 处理自定义对象
            if hasattr(obj, '__dict__'):
                attributes = {}
                for key, value in obj.__dict__.items():
                    if self.skip_private and key.startswith('_'):
                        continue
                    if not callable(value):
                        attributes[key] = value
                return {
                    '__type__': 'custom_object',
                    '__class__': obj.__class__.__name__,
                    'attributes': attributes
                }

            return str(obj)

        finally:
            self._obj_tracker.discard(obj_id)
            self._current_depth -= 1


# 测试高级编码器
class Person:
    def __init__(self, name, age, email):
        self.name = name
        self.age = age
        self.email = email
        self._internal_id = "person_001"


class Department:
    def __init__(self, name):
        self.name = name
        self.employees = []
        self._internal_id = "dept_001"

    def add_employee(self, employee):
        self.employees.append(employee)


dept = Department("技术部")
person = Person("李四", 25, "lisi@example.com")
dept.add_employee(person)

encoder = AdvancedJSONEncoder(indent=2, ensure_ascii=False, max_depth=5, skip_private=True)
result = encoder.encode(dept)
print("高级编码器结果:")
print(result)

运行结果:

高级编码器结果:
{
  "__type__": "custom_object",
  "__class__": "Department",
  "attributes": {
    "name": "技术部",
    "employees": [
      {
        "__type__": "custom_object",
        "__class__": "Person",
        "attributes": {
          "name": "李四",
          "age": 25,
          "email": "lisi@example.com"
        }
      }
    ]
  }
}

反序列化机制实现

完整的序列化解决方案还需要支持从JSON到对象的反向转换。通过实现自定义的object_hook函数,可以在JSON解析过程中识别特殊的类型标记,并执行相应的对象重构逻辑。

import datetime
import json
from decimal import Decimal


class CustomJSONEncoder(json.JSONEncoder):
    """
    自定义JSON编码器,支持多种复杂数据类型的序列化
    处理日期时间、集合、自定义对象等类型
    """

    def default(self, obj):
        # 处理日期时间对象
        if isinstance(obj, datetime.datetime):
            return {
                '__type__': 'datetime',
                'value': obj.isoformat()
            }

        if isinstance(obj, datetime.date):
            return {
                '__type__': 'date',
                'value': obj.isoformat()
            }

        # 处理集合类型
        if isinstance(obj, set):
            return {
                '__type__': 'set',
                'value': list(obj)
            }

        if isinstance(obj, tuple):
            return {
                '__type__': 'tuple',
                'value': list(obj)
            }

        # 处理Decimal类型
        if isinstance(obj, Decimal):
            return {
                '__type__': 'decimal',
                'value': str(obj)
            }

        # 处理自定义对象
        if hasattr(obj, '__dict__'):
            return {
                '__type__': 'custom_object',
                '__class__': obj.__class__.__name__,
                'attributes': obj.__dict__
            }

        # 处理dataclass对象
        if hasattr(obj, '__dataclass_fields__'):
            return {
                '__type__': 'dataclass',
                '__class__': obj.__class__.__name__,
                'fields': {field.name: getattr(obj, field.name)
                           for field in obj.__dataclass_fields__.values()}
            }

        return super().default(obj)

class JSONDecoder:
    """
    自定义JSON解码器,支持对象反序列化
    """

    def __init__(self):
        self.type_handlers = {
            'datetime': self._decode_datetime,
            'date': self._decode_date,
            'set': self._decode_set,
            'tuple': self._decode_tuple,
            'decimal': self._decode_decimal
        }

    def decode(self, json_string):
        return json.loads(json_string, object_hook=self._object_hook)

    def _object_hook(self, obj):
        if '__type__' in obj:
            type_name = obj['__type__']
            if type_name in self.type_handlers:
                return self.type_handlers[type_name](obj)
        return obj

    def _decode_datetime(self, obj):
        return datetime.datetime.fromisoformat(obj['value'])

    def _decode_date(self, obj):
        return datetime.date.fromisoformat(obj['value'])

    def _decode_set(self, obj):
        return set(obj['value'])

    def _decode_tuple(self, obj):
        return tuple(obj['value'])

    def _decode_decimal(self, obj):
        return Decimal(obj['value'])


# 测试完整的序列化和反序列化
original_data = {
    'timestamp': datetime.datetime.now(),
    'price': Decimal('99.99'),
    'tags': {'python', 'json', 'serialization'},
    'coordinates': (10, 20, 30)
}

# 序列化
json_data = json.dumps(original_data, cls=CustomJSONEncoder)
print("序列化:", json_data)

# 反序列化
decoder = JSONDecoder()
restored_data = decoder.decode(json_data)
print("反序列化成功,时间类型:", type(restored_data['timestamp']))

运行结果:

序列化: {"timestamp": {"__type__": "datetime", "value": "2025-06-08T13:03:42.075846"}, "price": {"__type__": "decimal", "value": "99.99"}, "tags": {"__type__": "set", "value": ["json", "serialization", "python"]}, "coordinates": [10, 20, 30]}
反序列化成功,时间类型: <class 'datetime.datetime'>

总结

自定义JSON编码器为Python应用程序提供了强大的数据序列化能力。通过扩展标准库的功能,我们能够处理复杂的对象结构,实现完整的数据持久化和传输方案。在实际应用中,需要注意安全性考虑,建立白名单机制来限制可重建的类型。同时要考虑性能优化,避免过度复杂的序列化逻辑影响系统效率。合理使用自定义JSON编码器,能够显著提升系统的数据处理能力,为构建可扩展的现代应用奠定坚实基础。通过掌握这些技术,开发者可以更好地应对复杂的数据序列化需求,构建高质量的Python应用程序。

相关推荐

SQL轻松入门(5):窗口函数(sql语录中加窗口函数的执行)

01前言标题中有2个字让我在初次接触窗口函数时,真真切切明白了何谓”高级”?说来也是一番辛酸史!话说,我见识了窗口函数的强大后,便磨拳擦掌的要试验一番,结果在查询中输入语句,返回的结果却是报错,Wh...

28个SQL常用的DeepSeek提示词指令,码住直接套用

自从DeepSeek出现后,极大地提升了大家平时的工作效率,特别是对于一些想从事数据行业的小白,只需要掌握DeepSeek的提问技巧,SQL相关的问题也不再是个门槛。...

从零开始学SQL进阶,数据分析师必备SQL取数技巧,建议收藏

上一节给大家讲到SQL取数的一些基本内容,包含SQL简单查询与高级查询,需要复习相关知识的同学可以跳转至上一节,本节给大家讲解SQL的进阶应用,在实际过程中用途比较多的子查询与窗口函数,下面一起学习。...

SQL_OVER语法(sql语句over什么含义)

OVER的定义OVER用于为行定义一个窗口,它对一组值进行操作,不需要使用GROUPBY子句对数据进行分组,能够在同一行中同时返回基础行的列和聚合列。...

SQL窗口函数知多少?(sql窗口怎么执行)

我们在日常工作中是否经常会遇到需要排名的情况,比如:每个部门按业绩来排名,每人按绩效排名,对部门销售业绩前N名的进行奖励等。面对这类需求,我们就需要使用sql的高级功能——窗口函数。...

如何学习并掌握 SQL 数据库基础:从零散查表到高效数据提取

无论是职场数据分析、产品运营,还是做副业项目,掌握SQL(StructuredQueryLanguage)意味着你能直接从数据库中提取、分析、整合数据,而不再依赖他人拉数,节省大量沟通成本,让你...

SQL窗口函数(sql窗口函数执行顺序)

背景在数据分析中,经常会遇到按某某条件来排名、并找出排名的前几名,用日常SQL的GROUPBY,ORDERBY来实现特别的麻烦,有时甚至实现不了,这个时候SQL窗口函数就能发挥巨大作用了,窗...

sqlserver删除重复数据只保留一条,使用ROW_NUMER()与Partition By

1.使用场景:公司的小程序需要实现一个功能:在原有小程序上,有一个优惠券活动表。存储着活动产品数据,但因为之前没有做约束,导致数据的不唯一,这会使打开产品详情页时,可能会出现随机显示任意活动问题。...

SQL面试经典问题(一)(sql经典面试题及答案)

以下是三个精心挑选的经典SQL面试问题及其详细解决方案,涵盖了数据分析、排序限制和数据清理等常见场景。这些问题旨在考察SQL的核心技能,适用于初学者到高级开发者的面试准备。每个问题均包含清晰的...

SQL:求连续N天的登陆人员之通用解答

前几天发了一个微头条:...

SQL四大排序函数神技(sql中的排序是什么语句)

在日常SQL开发中,排序操作无处不在。当大家需要排序时,是否只会想到ORDERBY?今天,我们就来揭秘SQL中四个强大却常被忽略的排序函数:ROW_NUMBER()、RANK()、DENSE_RAN...

四、mysql窗口函数之row_number()函数的使用

1、窗口函数之row_number()使用背景窗口函数中,排序函数rank(),dense_rank()虽说都是排序函数,但是各有用处,假如像上章节说的“同组同分”两条数据,我们不想“班级名次”出现“...

ROW_NUMBER()函数(rownumber函数与rank区别)

ROW_NUMBER()是SQL中的一个窗口函数(WindowFunction)...

Dify「模板转换」节点终极指南:动态文本生成进阶技巧(附代码)Jinja2引擎解析

这篇文章是关于Dify「模板转换」节点的终极指南,解析了基于Jinja2模板引擎的动态文本生成技巧,涵盖多源文本整合、知识检索结构化、动态API构建及个性化内容生成等六大应用场景,助力开发者高效利用模...

Python 最常用的语句、函数有哪些?

1.#coding=utf-8①代码中有中文字符,最好在代码前面加#coding=utf-8②pycharm不加可能不会报错,但是代码最终是会放到服务器上,放到服务器上的时候运行可能会报错。③...