Erik Ásland Erik Ásland - 2 months ago 6x
Javascript Question

How to extract a value from a Python dictionary using Javascript?

I have a Python dictionary that looks like this...

{u'reason': u'invalidQuery', u'message': u'Encountered " <ID> "asd "" at line 1, column 1.\nWas expecting:\n <EOF> \n ', u'location': u'query'}

How do I access the
value using Javascript? It is being passed to the front end via Django REST Framework, shouldn't that convert it to a JSON object automatically? It isn't...



import json

json_object = json.dumps(your_object)

In .html / .js

var json_object = {{json_object|safe}};

The .py side converts it to a valid JSON object. The tag in html escapes invalid json characters like "&"

In case you are sending your object as a string to your template then you have to convert it to JSON again via JSON for instance:


Or if the object is a string on the django views level:


To convert it into a json object