If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

NOTE OF CAUTION: This produces valid Javascript code but not necessarily valid-JSON code and therefore may not work with your JSON parser. It does work with major browsers that I've tested, but you are responsible for your code.

Sometimes you just need to send a datetime object to your client-side Javascript via JSON. This slice will show you how. First, take this code and put it in your favorite utility module:

import re
    import json
    import simplejson as json
__jsdateregexp__ = re.compile(r'"\*\*(new Date\([0-9,]+\))"')
class __JSONDateEncoder__(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return '**new Date(%i,%i,%i,%i,%i,%i)' % (obj.year,
        if isinstance(obj, date):
            return '**new Date(%i,%i,%i)' % (obj.year,
        return json.JSONEncoder.default(self, obj)

def dumps(obj):
    """ A (simple)json wrapper that can wrap up python datetime and date
    objects into Javascript date objects.
    @param obj: the python object (possibly containing dates or datetimes) for
        (simple)json to serialize into JSON

    @returns: JSON version of the passed object
    out = __jsdateregexp__.sub(r'\1', json.dumps(obj, cls=__JSONDateEncoder__))
    return unicode(out).decode('utf-8')

Now in your controller or view (where ever you serialize your data) , instead of importing json or simplejson, import the utility module that you placed the above code in. In the following example, we'll just call it "util".

import datetime
from util import dumps

def index():
    jsondata = dict(username=request.get_vars.username, logintime=datetime.datetime.now())
    return dict(jsondata=dumps(jsondata)

Note that this does not work with the JSON-RPC service since it handles it's own serialization that does not go through util.dumps.

Related slices

Comments (0)

Hosting graciously provided by:
Python Anywhere