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. JSON View Decorator by bryanpieper 1 year, 7 months ago
  2. JSON encode ISO UTC datetime by japerk 2 years, 10 months ago
  3. JSON decode datetime by japerk 2 years, 10 months ago
  4. Format transition middleware by limodou 4 years, 11 months ago
  5. Variable._resolve_lookup monkeypatch by showell 2 years, 2 months ago

Comments

(Forgotten your password?)