The Python Oracle

how to return a dictionary in python django and view it in javascript?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream

--

Chapters
00:00 Question
01:30 Accepted answer (Score 15)
01:44 Answer 2 (Score 10)
02:08 Answer 3 (Score 2)
02:29 Answer 4 (Score 1)
02:45 Thank you

--

Full question
https://stackoverflow.com/questions/6467...

Answer 2 links:
http://docs.python.org/library/json.html
http://www.json.org/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#javascript #python #django

#avk47



ACCEPTED ANSWER

Score 17


Very simply:

import json
data = {'val1' : 'this is x', 'val2' : True}
return HttpResponse( json.dumps( data ) )



ANSWER 2

Score 10


JSON is easiest way to transfer data(also you can use XML).

In python:

    import json
    data = {'val1': "this is x", 'val2': True}
    return HttpResponse(json.dumps(data))

In javascript:

    function (data) {
        data = JSON.parse(data);
        if (data["val2"]) {
            alert(data["val1"]);
        }
    }



ANSWER 3

Score 2


You can not directly use the python object you have to convert it into JSON string first Look into following documentation.

http://docs.python.org/library/json.html also http://www.json.org/




ANSWER 4

Score 1


Just specify the mimetype in HttpResponse

    return HttpResponse(
                        json.dumps({"status":False, "message":"Please enter a report name."}) ,
                        content_type="application/json"
                        )