fraction类型的Django对象不是JSON可序列化的

zu0ti5jz  于 2023-05-08  发布在  Go
关注(0)|答案(2)|浏览(118)
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from math import sqrt
from fractions import Fraction



def index(request):
    return render(request, 'home/index.html', {})

def multiplication(request):
    return render(request, 'multiplication/multiplication.html', {})

def compute(request):
    a = int(request.POST.get("a"))
    b = int(request.POST.get("b"))
    c = int(request.POST.get("c"))
    det = b*b-4*a*c
    rdet = sqrt(det)
    x1= (-b-rdet)/(2*a)
    x2= (-b+rdet)/(2*a)
    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": x3})

在我的view.py,我试图发送回我的html,通过var x3函数分数的结果
x3= Fraction(15,45),并使用JsonResponse发送结果。但我有一个错误消息:
fraction类型的对象不是json可序列化的
我不明白错在哪里。
谢谢你的帮助

juzqafwq

juzqafwq1#

您不能序列化分数,但可以创建自定义序列化程序并在其中传递分子和分母。

from django.http import JsonResponse
from django.views import View
from fractions import Fraction
import json

class FractionEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Fraction):
            return {"numerator": obj.numerator, "denominator": obj.denominator}
        return super().default(obj)

class generate_dummy_energy_usage(View):
    def get(self,request):
        a = 10
        b = 40
        c = 30
        det = b*b-4*a*c
        rdet = sqrt(det)
        x1 = (-b-rdet)/(2*a)
        x2 = (-b+rdet)/(2*a)
        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": x3}, encoder=FractionEncoder)

这是jsonresponse中的输出
[![在此处输入图像描述][1]][1]
而不是发送分数只是计算它并发送它作为字符串将是一个更简单的方法

px9o7tmv

px9o7tmv2#

document.querySelector("#fetch-call").addEventListener("click", event => {
    event.preventDefault();

    let form = new FormData();

    form.append("a", document.querySelector("#a").value);
    form.append("b", document.querySelector("#b").value);
    form.append("c", document.querySelector("#c").value);

    let csrfTokenValue = document.querySelector('[name=csrfmiddlewaretoken]').value;
    let request = new Request("{% url 'compute' %}", {method: 'POST',
                                                      body: form,
                                                      headers: {"X-CSRFToken": csrfTokenValue}})
    fetch(request)
        .then(response => response.json())
        .then(result => {
            let resultParagraph = document.querySelector("#operation");
            resultParagraph.innerHTML ="Le discriminant "+"\\(\\Delta\\)"+" =" + result["op_result"] ;
            MathJax.typeset();

            let resultParagraph2 = document.querySelector("#operation2");
            resultParagraph2.innerHTML ="La solution x1 est :"+"\\("+result["op_result5"]+"-"+"\\sqrt"+result["op_result"]+"\\over"+result["op_result4"]+"\\)"+" et la solution x2 est :"+"\\("+result["op_result5"]+"+"+"\\sqrt"+result["op_result"]+"\\over"+result["op_result4"]+"\\)";
            MathJax.typeset();
            
            let resultParagraph3 = document.querySelector("#operation3");
            resultParagraph3.innerHTML ="la valeur approchée de x1 est: " + result["op_result2"] + " et x2 est : "+ result["op_result3"];
            
            let resultParagraph4 = document.querySelector("#operation4");
            resultParagraph4.innerHTML ="facration " + result["op_result7"];
            
                   })
})

相关问题