Simple template filter to encode a variable to JSON format
Usage:
{% load json_filters %}
{% block content %} <script type="text/javascript"><![CDATA[ var items = {{ items|jsonify }}; ]]></script> {% endblock %}
I'm using JsonResponse for the views but I also want to have preloaded JSON data into the page output
1 2 3 4 5 6 7 8 9 10 11 12 13 | from django.core.serializers import serialize
from django.db.models.query import QuerySet
from django.utils import simplejson
from django.template import Library
register = Library()
def jsonify(object):
if isinstance(object, QuerySet):
return serialize('json', object)
return simplejson.dumps(object)
register.filter('jsonify', jsonify)
|
More like this
- Generate and render HTML Table by LLyaudet 5 days, 8 hours ago
- My firs Snippets by GutemaG 1 week, 1 day ago
- FileField having auto upload_to path by junaidmgithub 1 month, 2 weeks ago
- LazyPrimaryKeyRelatedField by LLyaudet 1 month, 3 weeks ago
- CacheInDictManager by LLyaudet 1 month, 3 weeks ago
Comments
if you pass simplejson.dumps a kwarg cls=django.core.serializers.json.DjangoJSONEncoder you get handling of datetime objects and decimals for free
#
You may want to use
mark_safe
on the results. In Django 1.2 I get HTML escaped quotation marks.#
Please login first before commenting.