Extend simplejson to understand closures, functors, generators and iterators

 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. Generate ICalendar Files with django-events by ElfSternberg 2 years, 7 months ago
  2. Ensure submitted slugs do not conflict with existing resolvable URLs by ElfSternberg 3 years, 11 months ago
  3. Generate Google Calendar links from django-event-calendar by ElfSternberg 2 years, 7 months ago
  4. Rails-like environments using Django by ElfSternberg 3 years, 7 months ago
  5. Django newforms ExtJS JSON Encoder by davidblewett 4 years, 11 months ago

Comments

(Forgotten your password?)