Login

Extend simplejson to understand closures, functors, generators and iterators

Author:
ElfSternberg
Posted:
May 20, 2009
Language:
Python
Version:
1.0
Tags:
ajax python json
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. JSON View Decorator by bryanpieper 4 years, 11 months ago
  2. JSON decode datetime by japerk 6 years, 2 months ago
  3. JSON encode ISO UTC datetime by japerk 6 years, 2 months ago
  4. ajax protocol for data by limodou 8 years, 4 months ago
  5. Format transition middleware by limodou 8 years, 4 months ago

Comments

Please login first before commenting.