【问题标题】:How to pass two JSONEncoder classes to the `cls` parameter of json.dumps?如何将两个 JSONEncoder 类传递给 json.dumps 的 `cls` 参数?
【发布时间】:2022-11-10 18:41:44
【问题描述】:

我想将类实例序列化为 JSON,但我的类包含 UUID 和 datetime 成员,所以我得到了这个 TypeError。

TypeError:日期时间类型的对象不是 JSON 可序列化的

通过为每个成员创建类,我成功地解决了每个问题(UUID 和日期时间问题):

class DTEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return str(obj)
        return json.JSONEncoder.default(self, obj)

class UUIDEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, uuid.UUID):
            # if the obj is uuid, we simply return the value of uuid
            return obj.hex
        return json.JSONEncoder.default(self, obj)

我使用这样的类:

convertedReadObject=json.dumps(ReadObject,cls=UUIDEncoder)

ReadObject 具有 UUID 成员。

但现在我需要这样做,但我需要将两个类传递给 cls 参数。

【问题讨论】:

标签: python json


【解决方案1】:

您可以使用 orjson https://github.com/ijl/orjson 支持日期时间以及各种其他 python 数据结构。它也很快

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多