深入理解Python对Json的解析_python


当前第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

  

# Dictionary mapping names to known classes

classes = {

 'Point' : Point

}

  

def unserialize_object(d):

 clsname = d.pop('__classname__', None)

 if clsname:

  cls = classes[clsname]

  obj = cls.__new__(cls) # Make instance without calling __init__

  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》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...