如何在FastAPI中返回支持重复键的可JSON序列化数据结构?
解决方案
因为字典键具有唯一性,重复键会被直接覆盖,而JSON结构支持的数组(对应Python的列表)允许包含重复结构的元素,所以可以改用列表嵌套字典的结构来保留所有信息——每个元素单独存储原始年龄和计算后的值,既符合JSON规范,也能完整保留所有条目。
修改后的代码
def example(*, current_age: int): const1 = 40 const2 = 45 const3 = 50 ages_list = (current_age, const1, const2, const3) my_final_return = [] for age in ages_list: my_final_return.append({ "age": age, "calculated_age": age * 2 }) return my_final_return
运行示例
传入current_age=40时,返回结果如下:
>>> example(current_age=40) [ {"age": 40, "calculated_age": 80}, {"age": 40, "calculated_age": 80}, {"age": 45, "calculated_age": 90}, {"age": 50, "calculated_age": 100} ]
FastAPI适配
如果要在FastAPI中使用,可以定义Pydantic模型规范返回结构,确保自动序列化JSON的正确性:
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class AgeEntry(BaseModel): age: int calculated_age: int @app.get("/calculate-ages", response_model=list[AgeEntry]) def calculate_ages(current_age: int): const1 = 40 const2 = 45 const3 = 50 ages_list = (current_age, const1, const2, const3) return [{"age": age, "calculated_age": age * 2} for age in ages_list]
这样接口返回的JSON结构会严格符合定义,同时完整保留所有重复的年龄条目和对应的计算值。
内容的提问来源于stack exchange,提问作者Ragnar
相关产品推荐
相关产品推荐

