5

一日一技:JSON如何快速转成对象?

 7 months ago
source link: https://www.kingname.info/2023/09/22/json-to-obj/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一日一技:JSON如何快速转成对象?

2023-09-22

45

362

1 分钟

我们知道,在Python里面,要把JSON转成字典是非常容易的,只需要使用json.loads(JSON字符串)就可以了。

但如果这个JSON转成的字典,嵌套比较深,那么要读取里面的数据就非常麻烦了。如下图所示:

20230921195257.png

如果我要读取把图中的end减去start字段,那么用字典的时候,代码要写成这样:

result = info['data'][0]['entities']['annotations'][0]['end'] - info['data'][0]['entities']['annotations'][0]['start']

光是看到这些方括号和单引号,就够让人头晕了。

但如果改成下面这样,看起来就清爽多了:

result = info.data[0].entities.annotations[0].end - info.data[0].entities.annotations[0].start

那么如何快速把一个嵌套很深的字典转换为对象呢?其实非常简单,使用Python自带的SimpleNamespace就可以了。

使用SimpleNamespace可以快速创建一个空对象,并设置它的属性,用法如下:

from types import SimpleNamespace

ins = SimpleNamespace(aa=1, bb=2, cc=3)

print(ins.bb)

运行效果如下图所示:

20230921202311.png

基于字典创建也非常简单:

from types import SimpleNamespace


data = {'aa': 1, 'bb': 2, 'cc': 3}
ins = SimpleNamespace(**data)

print(ins.bb)
20230921202359.png

对于深层嵌套的JSON字符串,我们在使用json.loads时,额外设置一个参数:object_hook,就可以实现递归式转换内层字典:

x = json.loads(JSON字符串, object_hook=lambda d: SimpleNamespace(**d))

如下图所示:

20230921203719.png

关于参数object_hook的具体用法,大家可以看官方文档


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK