Login

Extended JSON encoder

Author:
kcarnold
Posted:
June 13, 2008
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

The Django JSON encoder already extends the simplejson encoder a little; this extends it more and gives an example of how to go about further extension.

Hopefully newserializers (see the community aggregator today) will supercede this, but until then, it's useful.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models.query import QuerySet

def maybe_call(x):
    if callable(x): return x()
    return x


class JSONEncoder(DjangoJSONEncoder):
    '''An extended JSON encoder to handle some additional cases.

    The Django encoder already deals with date/datetime objects.
    Additionally, this encoder uses an 'as_dict' or 'as_list' attribute or
    method of an object, if provided. It also makes lists from QuerySets.
    '''
    def default(self, obj):
        if hasattr(obj, 'as_dict'):
            return maybe_call(obj.as_dict)
        elif hasattr(obj, 'as_list'):
            return maybe_call(obj.as_list)
        elif isinstance(obj, QuerySet):
            return list(obj)
        return super(JSONEncoder, self).default(obj)
json_encode = JSONEncoder().encode

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

adonm (on July 15, 2010):

I like =D

#

Please login first before commenting.