简体   繁体   中英

TypeError: object is not JSON serializable in DJango 1.8 Python 3.4

I'm using DJango 1.8 and Python 3.4

When the below view is being ran, Django throws Type Error - Object is not JSON Serializable

Views.py

from django.http import HttpRequest,HttpResponse
from django.http import JsonResponse
from json import dumps

def get_stats(request):
    if request.method == "POST":
        srch_dropV = request.POST['srch_dropAJ']
    else:
        srch_dropV = ''
    if(srch_dropV == 'Green'):
        students = GreenBased.objects.all()
    if(srch_dropV == 'Yellow'):
        students = YellowBased.objects.all()
    response_data = {}
    try:
        response_data['result'] = 'Success'
        response_data['message'] = list(students)
    except:
        response_data['result'] = 'Ouch!'
        response_data['message'] = 'Script has not ran correctly'
    return HttpResponse(JsonResponse(response_data), content_type="application/json")

I'm trying to read couple of rows from mysql database and display it on the html file, I'm facing below error message when above view is being ran

TypeError: YellowBased: YelloBased object is not JSON serializable

In HTML Page, I have a drop down list.. based on the option that is selected, my Ajax would return me the records that were fetched from mysql table.

Models.py

class GreenBased(models.Model):
    NumOfStudents = models.CharField(max_length=300,blank=True)
    Green = models.CharField(max_length=300,blank=True)
    class Meta:
        managed = False
        db_table = "GreenStats"

class YelloBased(models.Model):
    NumOfStudents = models.CharField(max_length=300,blank=True)
    Yellow = models.CharField(max_length=300,blank=True)
    class Meta:
        managed = False
        db_table = "YellowStats"

GreenStats and YellowStats tables contains only 2*2 rows in mysql Can someone please help me to identify this issue ?

You have to serialize your student objects list, try something like this:

from django.http import HttpRequest,HttpResponse
from django.http import JsonResponse
from json import dumps
from django.core import serializers


def get_stats(request):
    if request.method == "POST":
        srch_dropV = request.POST['srch_dropAJ']
    else:
        srch_dropV = ''
    if(srch_dropV == 'Green'):
        students = GreenBased.objects.all()
    if(srch_dropV == 'Yellow'):
        students = YellowBased.objects.all()
    response_data = {}
    try:
        response_data['result'] = 'Success'
        response_data['message'] = serializers.serialize('json', students)
    except:
        response_data['result'] = 'Ouch!'
        response_data['message'] = 'Script has not ran correctly'
    return JsonResponse(response_data)

Notice the line change in :
response_data['message'] = serializers.serialize('json', students)

Also JsonResponse does the trick on its own, so no need to wrap it in a HttpResponse .

check the docs for more customization: https://docs.djangoproject.com/en/1.8/topics/serialization/

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM