TypeError:类型为'int32'的对象不可JSON序列化

2022-02-22 00:00:00 python django django-views ajax
我必须选择字典中已发布症状的症状。它工作正常。但是对于某些症状,TypeError会显示在命令提示符中,并且所有症状都会在命令提示符中打印,但不会显示在HTML页面中。 以下是我的代码

views.py

def predict(request):
sym=request.POST.getlist('symptoms[]')
sym=list(map(int,sym))
diseaseArray=[]
diseaseArray=np.array(diseaseArray,dtype=int)
dictArray=[]
for dicti in dictionary:
    if (set(sym)<= set(dicti['symptoms']) and len(sym)!= 0) or [x for x in sym if x in dicti['primary']]:
        diseaseArray=np.append(diseaseArray,dicti['primary'])
        diseaseArray=np.append(diseaseArray,dicti['symptoms'])
diseaseArray=list(set(diseaseArray))
print(diseaseArray)
for i in diseaseArray:
    if i not in sym:
        dict={'id':i}
        dictArray.append(dict)
        print(dictArray)
for j in dictArray:
    symptoms=Symptom.objects.get(syd=j['id'])
    j['name']=symptoms.symptoms
    print(j['name'])
print(len(dictArray))
return JsonResponse(dictArray,safe=False)

模板

$('.js-example-basic-multiple').change(function(){
  $('#suggestion-list').html('');
  $('#suggestion').removeClass('invisible');

  $.ajax({
  url:"/predict",
  method:"post",
  data:{
    symptoms: $('.js-example-basic-multiple').val(),
  },
  success: function(data){

      data.forEach(function(disease){
      console.log(disease.name)
        $('#suggestion-list').append('<li>'+disease.name+'<li>')
        $('#suggestion-list').removeClass('invisible');
    });



  }

  });

解决方案

diseaseArray中每个元素的类型为np.int32,定义如下:

diseaseArray=np.array(diseaseArray,dtype=int)  # Elements are int32

int32无法通过视图返回的JsonResponse序列化为JSON。

要修复,请将id值转换为常规int

def predict(request):
    ...
    for i in diseaseArray:
        if i not in sym:
            dict={'id': int(i)}  # Convert the id to a regular int
            dictArray.append(dict)
            print(dictArray)
    ...

相关文章