Erik Ásland Erik Ásland - 4 months ago 9
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
u'message'
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...

Answer

In views.py

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:

JSON.parse("{{json_object}}");

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

json.loads(your_string)

To convert it into a json object

Comments