简体   繁体   中英

DJANGO upgrade error: is not JSON serializable

This was my code in django 1.6 ( working good) I upgraded to django 1.7. First simplejson is depracated : i changed simplejson to json,But i receive the same error always is not json serializable.

Any ideas ?

Views:

def request_to_json(request):    
    post_data = request.body 
    json_data = simplejson.loads(post_data)
    return json_data 

def receiver(request):
    try:
        json_data = request_to_json(request)
        user_id=json_data['user_id'];
        site_id=json_data['site_id'];
  # A variable to return to the app
        response = 'Ok'

    except:
        response = sys.exc_info()[0]

    return HttpResponse(simplejson.dumps(response))   

Error

TypeError at /views/receiver/
<class 'TypeError'> is not JSON serializable
Request Method: POST
Request URL:    http://localhost:8000/views/receiver/
Django Version: 1.7
Exception Type: TypeError
Exception Value:    
<class 'TypeError'> is not JSON serializable
Exception Location: C:\Python34\lib\json\encoder.py in default, line 173
Python Executable:  C:\Python34\python.EXE
Python Version: 3.4.1
Python Path:    
['C:\\workspace-eclipse\\IndoorPositioning',
'C:\\Python34\\lib\\site-packages\\setuptools-5.4.2-py3.4.egg',
'C:\\Windows\\system32\\python34.zip',
'C:\\Python34\\DLLs',
'C:\\Python34\\lib',
'C:\\Python34',
'C:\\Python34\\lib\\site-packages']
 Server time:   Sat, 13 Sep 2014 12:18:36 +0200

Your exception handler is raising an exception. You are trying to serialise the entire exception object to json to return to the user. Instead get a string representation of the exception and return that:

def receiver(request):
    try:
        ...
    except:
        response = "%s" % sys.exc_info()[0]
    return HttpResponse(simplejson.dumps(response)) 

(It's not a great idea to be directly returning internal exception messages, you should probably try and specifically catch the exception and return a user-friendly message instead of the actual exception)

If you want to see why you are getting an exception in your code, you need to allow the exception to be raised. Get rid of the try .. catch block and you will see the actual exception that is being raised with regards the request_to_json function

By the looks of it, the problem is that you are trying to serialize the entire body of the request :

 post_data = request.body 

which simplejson doesn't like

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