Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a JSON response using Django and Python

I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.

This is the server-side script:

/* RECEIVE VALUE */ $validateValue=$_POST['validateValue']; $validateId=$_POST['validateId']; $validateError=$_POST['validateError'];  /* RETURN VALUE */ $arrayToJs = array(); $arrayToJs[0] = $validateId; $arrayToJs[1] = $validateError;  if($validateValue =="Testuser"){  // Validate??     $arrayToJs[2] = "true";       // RETURN TRUE     echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';  // RETURN ARRAY WITH success } else{     for($x=0;$x<1000000;$x++){         if($x == 990000){             $arrayToJs[2] = "false";             echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';   // RETURNS ARRAY WITH ERROR.         }     } } 

And this is the converted code

def validate_user(request):     if request.method == 'POST':         vld_value = request.POST.get('validateValue')         vld_id = request.POST.get('validateId')         vld_error = request.POST.get('validateError')          array_to_js = [vld_id, vld_error, False]          if vld_value == "TestUser":             array_to_js[2] = True             x = simplejson.dumps(array_to_js)             return HttpResponse(x)         else:             array_to_js[2] = False             x = simplejson.dumps(array_to_js)             error = 'Error'             return render_to_response('index.html',{'error':error},context_instance=RequestContext(request))     return render_to_response('index.html',context_instance=RequestContext(request)) 

I'm using simplejson to encode the Python list (so it will return a JSON array). I couldn't figure out the problem yet. But I think that I did something wrong about the 'echo'.

like image 951
Switch Avatar asked Mar 11 '10 19:03

Switch


People also ask

Can Django return JSON?

Django provides a built-in class JsonResponse that makes returning JSON easy. By default, the JsonResponse class sets a Content-Type header of application/json.

What is JSON response in Django?

Django JsonResponse JsonResponse is an HttpResponse subclass that helps to create a JSON-encoded response. Its default Content-Type header is set to application/json. The first parameter, data , should be a dict instance.


1 Answers

I usually use a dictionary, not a list to return JSON content.

import json  from django.http import HttpResponse  response_data = {} response_data['result'] = 'error' response_data['message'] = 'Some error message' 

Pre-Django 1.7 you'd return it like this:

return HttpResponse(json.dumps(response_data), content_type="application/json") 

For Django 1.7+, use JsonResponse as shown in this SO answer like so :

from django.http import JsonResponse return JsonResponse({'foo':'bar'}) 
like image 178
Tom Avatar answered Sep 22 '22 05:09

Tom