Created
August 14, 2012 22:03
-
-
Save clooth/3353414 to your computer and use it in GitHub Desktop.
Django json templatetag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.template import Library | |
from django.core.serializers import serialize | |
from django.core.serializers.json import DjangoJSONEncoder | |
from django.utils import simplejson | |
from django.utils.safestring import mark_safe | |
register = Library() | |
@register.filter | |
def json(object, fields=None): | |
if not fields: | |
raw_data = serialize('python', object) | |
else: | |
raw_data = serialize('python', object, fields=fields.split(',')) | |
actual_data = [d['fields'] for d in raw_data] | |
return mark_safe(simplejson.dumps(actual_data, cls=DjangoJSONEncoder)) | |
json.is_safe = True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment