Login

Extend simplejson to understand closures, functors, generators and iterators

Author:
ElfSternberg
Posted:
May 20, 2009
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

For most applications, simplejson.dumps() is enough. But I’m especially fond of iterators, generators, functors (objects with a __call__() method) and closures, dense components that express one thought well: the structure of a tree, or the rows of a database, to be sent to the browser. The routine dumps() doesn’t understand any of those things, but with a simple addition, you can plug them into your code and be on your way without headache. Dumps() just calls JSONEncoder(), and JSONEncoder has a routine for extending its functionality.

The routine is to override a method named default() (why “default?” I have no idea) and add the object types and signatures you want to send to the browser. Normally, this exists for you to provide custom “object to JSON” handlers for your objects, but there’s nothing custom about iterators, generators, functors and closures. They are native Python objects. This snippet provides the functionality needed by JSONEncoder to correctly dereference these useful Python objects and render their contents.

(Originally posted here )

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from django.utils.simplejson.encoder import JSONEncoder
from django.utils import simplejson

class ExtJsonEncoder(JSONEncoder):
    def default(self, c):
        # Handles generators and iterators
        if hasattr(c, '__iter__'):
            return [i for i in c]

        # Handles closures and functors
        if hasattr(c, '__call__'):
            return c()

        return JSONEncoder.default(self, c)

def json(s, **kw):
    kw.update({'cls', ExtJsonEncoder})
    return simplejson.dumps(s, **kw)

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

Please login first before commenting.