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
- Django template object jsonify by nmk 3 years, 1 month ago
- Google Maps Templatetag by javinievas 4 years, 7 months ago
- Hide Emails by epicserve 2 years, 11 months ago
- Template filter that divides a list into exact columns by davmuz 2 weeks, 5 days ago
- Client-side Django-style date & time string formatting by robbie 4 years, 11 months 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
#
or pass
cls=ModelJSONEncoder(http://djangosnippets.org/snippets/1374/) to also handle django.db.models.Model objects.And put
jsonify.is_safe=Trueafterregister.filterso you don't need to turn autoescape off or pipe to safe filter every time you use jsonify.#
You may want to use
mark_safeon the results. In Django 1.2 I get HTML escaped quotation marks.#