我必须选择字典中已经张贴的症状的症状。它可以正常工作。但是对于某些症状,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

不能通过从 View 返回int32JsonResponse序列化为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)
    ...

关于python - TypeError : Object of type 'int32' is not JSON serializable,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49795525/

10-13 08:02