5

Is there a way to pass JSON objects to the front end of a web template if using the Django framework or Python in general?

For example, if I want to send an object that has two arrays as properties (let's say xvalues and yvalues), how would I be able to use JavaScript or jQuery to do an Ajax call to obtain the object that has the properties?

2
  • 1
    you mean like transforming a list to a json object and passing it to your template? or sending the json as a response to an Ajax request? can you explain a little more your question? :p Commented Aug 11, 2011 at 2:50
  • see above for the edits. Commented Aug 11, 2011 at 3:00

5 Answers 5

7

If I understand you correctly, you want to render some JSON in your HTML output.

To do this, pass the json-encoded object from the view to the template:

views.py:

import json def myview(request): obj = {"a": 1, "b": 2} return render_to_response("template.html", {"obj_as_json": json.dumps(obj)}) 

template.html:

<html> <head> <script type="text/javascript"> var obj = {{ obj_as_json|safe }}; </script> </head> ... </html> 

Will render as:

... <script type="text/javascript"> var obj = {"a": 1, "b": 2}; ... 

Note that json.dumps only works with dictionaries containing simple data types. Django has support for serializing model objects to json, using:

from django.core import serializers obj_as_json = serializers.serialize("json", my_model_object) 

Update: note that you need to use "safe" to get this:

 var obj = {"items": [{"human": "Genesis", "usfm": "GEN"},],} 

instead of this:

 var obj = {&quot;items&quot;: [{&quot;human&quot;: &quot;Genesis&quot;, &quot;usfm&quot;: &quot;GEN&quot;},],} 
Sign up to request clarification or add additional context in comments.

1 Comment

He was asking for an Ajax case ;) Also, I think your solution won't fully work, because Django will escape some parts of the json result (typically double quotes which wille become &quot; html entities). You'll have to call mark_safe() on the json somewhere before passing it to the template.
6

Sure, just setup a view that returns JSON and make a request to it. Here's a simple example:

import json from django.http import HttpResponse from django.template import Template, Context def ajax(request): """returns json response""" return HttpResponse(json.dumps({'foo': 'bar'}), mimetype='application/json') def index(request): """simple index page which uses jquery to make a single get request to /ajax, alerting the value of foo""" t = Template(""" <!doctype html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> <script type="text/javascript"> $.get('/ajax/', function(data) { alert(data['foo']); }); </script> </head> </html>""") return HttpResponse(t.render(Context())) # urlconf urlpatterns = patterns('', (r'^$', index), (r'^ajax/', ajax), ) 

Comments

5

Complementing zeekay answer, if you want to send only an object you could do a json dump, for example:

import json def my_ajax_view(request): if not request.is_ajax(): raise Http404 data_dict = getmydata() #lets supose is a dict return HttpResponse(json.dumps(data_dict)) 

That way you will receive that data via your ajax success and do whatever you want with it.

You can send over lists too, when you receive your response sometimes you will need to do a JSON.parse on data (sometimes cause when you send a dictionary I think is not necessary)

Comments

2

Unfortunately, the present answers are a bit outdated, here's how to do this with more recent versions of Django (including Django > 2.0):

Use JsonResponse, a subclass of HttpResponse, for this:

# views.py from django.http import JsonResponse def get_coords(request): """returns json response""" json_data = {'xval': 10, 'yval': 10} return JsonResponse(json_data) 

It assumes a dict as parameter, but you can pass any JSON-serializable, in principle. I would discourage you from doing so, but if you pass an object that is not a dict you need to set the parameter safe=False.

The ajax-request might look something like:

# index.html ... <head> ... <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $.get("{% url 'ajax_get_coords' %}", function(data) { var xval = data.xval; var yval = data.yval; ... }); </script> ... 

With the corresponding urlconfig:

# urls.py urlpatterns = [ path('ajax_coords/', views.get_coords, name='ajax_get_coords'), ... 

Comments

1

As of Django 2.1 there is another way to pass JSON objects to the front-end by including them in the template and using the json_script template filter. This will create a script tag in the HTML and include the JSON within that. This is useful for including the JSON in the download of the HTML page.

Your template would use the tag like so:

{{ your_json_object | json_script: "element_id" }} 

Where your_json_object is a template variable containing an object that can be parsed into JSON.

The HTML output would be:

<script id="element_id">{['json', 'object']}</script> 

And you can access it in a later Javascript file with:

let my_json = JSON.parse(document.getElementByID('element_id').textContent) 

Checkout the documentation.

1 Comment

Small mistake: remove the space after ":", i.e. the template tag should be: {{ your_json_object | json_script:"element_id" }}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.