深入理解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的pip怎么用

Python xlsxwriter模块创建aexcel表格

四六级成绩还可以这样查?Python助你装b一步到位!!!

Python怎么打开文件的路径?

Python requests快速入门介绍

Python怎么输入变量

Python中缩进是什么

Python中range函数怎么用

Python中range()函数怎么用

为什么黑客都使用Python

更多相关阅读请进入《Python》频道 >>




打赏

取消

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

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

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

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

评论

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