One skill a day: How to quickly convert JSON into objects?

Original link: https://www.kingname.info/2023/09/22/json-to-obj/

We know that in Python, it is very easy to convert JSON into a dictionary, just use json.loads(JSON字符串) .

But if the dictionary converted from JSON is deeply nested, it will be very troublesome to read the data inside. As shown below:

20230921195257.png

If I want to read and subtract start field from end in the picture, then when using a dictionary, the code should be written like this:

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

Just seeing these square brackets and single quotes is enough to make you dizzy.

But if you change it to the following, it will look much cleaner:

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

So how to quickly convert a deeply nested dictionary into an object? It’s actually very simple, just use SimpleNamespace that comes with Python.

Use SimpleNamespace to quickly create an empty object and set its properties. The usage is as follows:

 1
2
3
4
5
 from types import SimpleNamespace

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

print (ins.bb)

The running effect is shown in the figure below:

20230921202311.png

Creating based on a dictionary is also very simple:

 1
2
3
4
5
6
7
 from types import SimpleNamespace


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

print (ins.bb)

20230921202359.png
For deeply nested JSON strings, when we use json.loads , we set an additional parameter: object_hook to achieve recursive conversion of the inner dictionary:

 1
 x = json.loads(JSON string, object_hook= lambda d: SimpleNamespace(**d))

As shown below:

20230921203719.png

For the specific usage of the parameter object_hook , you can read the official documentation.

This article is reproduced from: https://www.kingname.info/2023/09/22/json-to-obj/
This site is for inclusion only, and the copyright belongs to the original author.