Friday, October 8, 2010

json

json 库允许在 python 中将对象转换到 json 格式或者将 json 格式的文本转换成为 python 对象。

python 内置的几种对象已经有现成的转换方法了,如 dictionary 将被转换成为 JSONObject,list 会被转换成为 JSONArray,等等。我们所需要做的只是简单的调用 json.dump() 和 json.load() 即可。两者可以指定用于解析的 python 类(cls)。另外有 dumps 和 loads 命令用于转换成为字符串。

对于一些特殊的 python 对象,需要自己写 JSON 的 encoder 和 decoder,json 也提供了基本的类(json.JSONEncoder 与 json.JSONDecoder)供继承。一般需要重载 default 方法即可。下面是一个简单的例子:
#!/usr/bin/python

import json

class ComplexEncoder( json.JSONEncoder ):
    def default( self, obj ):
        if isinstance( obj, complex ):
            return {'real': obj.real, 'imag': obj.imag }
        return super.default( obj )

if __name__ == '__main__':
    print json.dumps( 1 + 2j, cls=ComplexEncoder )
运行结果如下:
$ ./test11.py 
{"real": 1.0, "imag": 2.0}

No comments:

Post a Comment