Python CJSON encoding custom objects

I am updating an old project that used an old version of cjson to speed up its json encoding. It also has a custom class called JSONString (which sets a string to its 'value' property) that is used for communicating with the database.

It used to call cjson.encode((dict containing a JSONString), (custom encoding funct for JSONSTRING)) but the newer version of cjson has changed its parameters to only accepting one argument, and not exposing any other functions that could allow customizations of the encoding process. Encoding the dict without the custom encoder throws an EncodeError (object is not JSON encodable).

The options I have now are to either find out how to use custom encoders in cjson, modify the cjson source (trying to avoid patching libraries), or make it so the JSONString type inserted into the dict is converted to a string before the operation, but I am trying to avoid placing 'fixes' all over the code (compartmentalization and re-usability and all that). Modifying JSONString in some way so that the encoder takes the string value of it instead of throwing an exception would work too, but I don't know enough of python's quirks to do this. I can understand why cjson might not allow custom encoders (speed reasons) but if there is no way I might just have to find something else.

Any suggestions would be greatly appreciated.


Looking through my unanswered posts and remembered I never marked this as answered. Yavar's post did help; there is an enhanced version of cjson for python. It works well but has some interesting name collisions at times so be aware of that.

http://python.cx.hu/python-cjson/

链接地址: http://www.djcxy.com/p/47794.html

上一篇: 编码来创建字符串

下一篇: Python CJSON编码自定义对象