相关疑难解决方法(0)

如何使类JSON可序列化

如何使Python类可序列化?

一个简单的课程:

class FileItem:
    def __init__(self, fname):
        self.fname = fname
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能得到输出:

>>> import json

>>> my_file = FileItem('/foo/bar')
>>> json.dumps(my_file)
TypeError: Object of type 'FileItem' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

没有错误(__CODE__)

python serialization json

730
推荐指数
19
解决办法
61万
查看次数

覆盖 FastAPI 中 jsonable_encoder 的默认编码器

我有使用Fast API 的代码,看起来像这样:

class EnumTestT(Enum):
    test_t_value = 0

object = { 
    test: test_t_value
}

enum_mapping = {
    test_t_value: "Test"
}

def enum_encoder(val: EnumTestT) -> str:
    return enum_mapping[val]

custom_encoder = {
    EnumTestT: enum_encoder
}

@app.get("/test")
async def test_get():
    return jsonable_encoder(object, custom_encoder=custom_encoder)
Run Code Online (Sandbox Code Playgroud)

问题是jsonable_encoder在默认编码器之后应用自定义编码器。有什么方法可以在默认编码器之前应用它们。因为对于Enum任何派生类,报告的是枚举值而不是映射值。

python fastapi

9
推荐指数
2
解决办法
2万
查看次数

标签 统计

python ×2

fastapi ×1

json ×1

serialization ×1