Login

jsonify template filter

Author:
skam
Posted:
April 25, 2007
Language:
Python
Version:
.96
Score:
7 (after 7 ratings)

Simple template filter to encode a variable to JSON format

Usage:

{% load json_filters %}

{% block content %} &lt;script type="text/javascript"&gt;<![CDATA[ var items = {{ items|jsonify }}; ]]>&lt;/script&gt; {% 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

  1. codigo alto nivel by MrRocklion 1 month ago
  2. Load template from specific app by Krzysiek555 1 month, 3 weeks ago
  3. PostgreSQL JSON subqueries by dolamroth 1 month, 3 weeks ago
  4. "Magic Link" Management Command by webology 7 months ago
  5. Closest ORM models to a latitude/longitude point by simonw 7 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

#

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.

#

Please login first before commenting.