How to Creat a JSON response using Django and Python

0 votes

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 think that I did something wrong about the 'echo'.

Aug 6, 2020 in Python by kartik
• 37,510 points
2,915 views

1 answer to this question.

0 votes

Hello @kartik,

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  :

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

Hope it helps!!
Thank You!

answered Aug 6, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

how to send post request to a webpage using cookies and headers in python to scrape the webpage ?

Hey @Avinash, Regarding your query, I would suggest ...READ MORE

answered Sep 29, 2020 in Python by Roshni
• 10,520 points
2,466 views
0 votes
1 answer

How to merge multiple json objects into a single json object using python

You may do like this but it ...READ MORE

answered Nov 22, 2020 in Python by Gitika
• 65,910 points
18,625 views
+2 votes
2 answers

How to make a laplacian pyramid using OpenCV python?

down voteacceptTheeThe problem is that you're iterating ...READ MORE

answered Apr 3, 2018 in Python by charlie_brown
• 7,720 points
4,481 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
2,080 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
1,227 views
0 votes
1 answer

How to perform HTML decoding/encoding using Python/Django?

Hello, For html encoding, there's cgi.escape from the standard library: >> ...READ MORE

answered May 7, 2020 in Python by Niroj
• 82,880 points
12,490 views
0 votes
1 answer

How to get the latest file in a folder using python?

Hello @kartik,  would suggest using glob.iglob() instead of the glob.glob(), as ...READ MORE

answered May 27, 2020 in Python by Niroj
• 82,880 points
10,991 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP