python-cjson 1.0.3x2 released

Ferenczi Viktor python at cx.hu
Wed Mar 28 01:33:02 CEST 2007


This is an enhanced version of python-cjson, the fast JSON encoder/decoder.

Qiangning Hong submitted a patch to fix segfault with Python 2.5 on 64 bit
platforms. Version python-cjson 1.0.3x2 released to incorporate this patch.

It's numbered 1.0.3x, where x stands for eXtension.

The main improvement is the ability to extend the JSON encoder and decoder
with extensions functions to serialize/unserialize objects not in the
original JSON specification. This is achieved without sacrificing the speed
and stability of the original implementation. Please send bug reports to
python at cx.hu and do not contact the original author (Dan Pascu) about this
version.

Download and more information:
http://cx.hu/python-cjson/

Example to encode/decode python date objects as JavaScript Date:

import re
import cjson
import datetime

# Encoding Date objects:
def dateEncoder(d):
    assert isinstance(d, datetime.date)
    return 'new Date(Date.UTC(%d,%d,%d))'%(d.year, d.month, d.day)

json=cjson.encode([1,datetime.date(2007,1,2),2], extension=dateEncoder)
assert json=='[1, new Date(Date.UTC(2007,1,2)), 2]'

# Decoding Date objects:
re_date=re.compile('^new\sDate\(Date\.UTC\(.*?\)\)')
def dateDecoder(json,idx):
    json=json[idx:]
    m=re_date.match(json)
    if not m: raise 'cannot parse JSON string as Date object: %s'%json[idx:]
    args=cjson.decode('[%s]'%json[18:m.end()-2])
    dt=datetime.date(*args)
    return (dt,m.end()) # must return (object, character_count) tuple

data=cjson.decode('[1, new Date(Date.UTC(2007,1,2)), 2]',
extension=dateDecoder)
assert data==[1,datetime.date(2007,1,2),2]



More information about the Python-announce-list mailing list