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

Django中Fraction对象无法JSON序列化问题求助

问题解决:Fraction对象无法JSON序列化的处理方法

问题原因

JSON序列化只支持基础数据类型(字符串、整数、浮点数、列表、字典等),而Fraction是Python的自定义对象,Django默认的JSON序列化器无法识别它,所以会抛出object of type fraction is not json serializable错误。

解决方案

这里给你三种实用的处理方式,根据需求选择:

1. 转为字符串(保留分数格式)

如果前端需要显示1/3这种分数形式,直接把Fraction对象转成字符串:

x3 = Fraction(15, 45)
return JsonResponse({
    "op_result": det, 
    "op_result2": x1, 
    "op_result3": x2, 
    "op_result4": 2*a, 
    "op_result5": -b, 
    "op_result6": c,
    "op_result7": str(x3)  # 转成字符串
})

2. 转为浮点数(获取数值)

如果前端需要用这个值做计算,转成浮点数即可:

x3 = Fraction(15, 45)
return JsonResponse({
    # ...其他参数
    "op_result7": float(x3)  # 转成浮点数,结果是0.3333333333333333
})

3. 自定义序列化器(保留分子分母结构)

如果需要把分子和分母分开传给前端,让前端自己处理格式,可以自定义JSON编码器:
首先在view.py里导入相关模块并定义编码器:

from django.http import JsonResponse
from django.core.serializers.json import DjangoJSONEncoder
from fractions import Fraction

class FractionEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, Fraction):
            # 返回包含分子分母的字典
            return {"numerator": obj.numerator, "denominator": obj.denominator}
        # 其他类型用默认处理
        return super().default(obj)

然后在返回时指定编码器:

x3 = Fraction(15, 45)
return JsonResponse({
    # ...其他参数
    "op_result7": x3
}, encoder=FractionEncoder)

这样前端拿到的op_result7会是{"numerator":1,"denominator":3}。

内容的提问来源于stack exchange,提问作者jean-michel ligner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 23:30:06