当前第2页 返回上一页
还可以通过指定“函数”来进行转换。
用函数来指定序列化的方法,即将对象的“属性-值”对变成字典对,函数返回一个字典,然后json.dumps
会格式化这个字典。
如果是通过函数将json变成对象,首先获得类名,然后通过__new__
来创建一个对象(不调用初始化函数),然后将json字典的各个属性赋给对象。
使用函数指定json转换方式Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | def serialize_instance(obj):
d = { '__classname__' : type (obj).__name__ }
d.update( vars (obj))
return d
classes = {
'Point' : Point
}
def unserialize_object(d):
clsname = d.pop( '__classname__' , None )
if clsname:
cls = classes[clsname]
obj = cls .__new__( cls )
for key, value in d.items():
setattr (obj, key, value)
return obj
else :
return d
|
使用方法如下:
1 2 3 4 5 6 7 8 9 10 11 | >>> p = Point( 2 , 3 )
>>> s = json.dumps(p, default = serialize_instance)
>>> s
'{"__classname__": "Point", "y": 3, "x": 2}'
>>> a = json.loads(s, object_hook = unserialize_object)
>>> a
<__main__.Point object at 0x1017577d0 >
>>> a.x
2
>>> a.y
3
|
相关推荐:
Python对JSON的解析详解
Python对Json字符串判断的方法实例
深入理解python对json的操作总结
以上就是深入理解Python对Json的解析_python的详细内容,更多文章请关注木庄网络博客!!
返回前面的内容
相关阅读 >>
Python 开发工具和框架安装实例步骤
Python强大之处在哪里
Python实现简单文本字符串处理的方法
如何用Python计算基本统计值?
Python如何判断一个文件是否存在
Python怎么学
Python的numpy库中将矩阵转换为列表等函数的方法_Python
Python儿童编程有必要学吗
Python验证码识别教程之利用投影法、连通域法分割图片
Python中迭代相关的简单介绍(附代码)
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 深入理解Python对Json的解析_python