jsonify template filter

 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

  1. Django template object jsonify by nmk 4 years, 5 months ago
  2. Hide Emails by epicserve 4 years, 2 months ago
  3. Generic CSV Export by zbyte64 4 years, 11 months ago
  4. Git Revision Template Tag by sbaechler 6 months, 1 week ago
  5. FCKEditor replace all vLargeTextField in admin by aronchi 4 years, 6 months ago

Comments

sk1p (on July 10, 2007):

if you pass simplejson.dumps a kwarg cls=django.core.serializers.json.DjangoJSONEncoder you get handling of datetime objects and decimals for free

#

ron (on July 9, 2010):

or pass cls=ModelJSONEncoder (http://djangosnippets.org/snippets/1374/) to also handle django.db.models.Model objects.

And put jsonify.is_safe=True after register.filter so you don't need to turn autoescape off or pipe to safe filter every time you use jsonify.

#

vdboor (on September 12, 2010):

You may want to use mark_safe on the results. In Django 1.2 I get HTML escaped quotation marks.

#

(Forgotten your password?)