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?
Send JSON Data from the Client SideUse JSON. stringify() to convert the JavaScript object into a JSON string. Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET, or POST method by assigning the JSON string to a variable.
Since Django 1.9, the popular Python framework has supported jsonb and several other Postgres-specific fields. Native Django support means that creating jsonb fields, using them in your models, inserting data into them, and querying from them are all possible with Django's ORM.
Django REST Framework JSON API is a library for creating JSON:API backends using the Django framework, built on top of the Django REST Framework library.
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),
)
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 = {"items": [{"human": "Genesis", "usfm": "GEN"},],}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With