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:
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 |
from types import SimpleNamespace |
The running effect is shown in the figure below:
Creating based on a dictionary is also very simple:
1 |
from types import SimpleNamespace |
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:
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.