You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<p>There are many ways you can convert a Json object to Python classes. This tools uses one of these ways which uses static functions to map dictionary key values to type safe Python properties and classes. Here are the steps to convert Json to Python classes: </p>
2
+
<h3><strong>1. Create a DataClass for each Json Root Node</strong></h3>
3
+
<p>Let's take the below JSON string as example and work with it during the steps:</p>
4
+
<pre><code>{
5
+
""Test"":<br /> {
6
+
""id"":4,
7
+
""userid"":""user_id_value"",
8
+
""users"":[
9
+
{
10
+
""id"":""2"",
11
+
""name"":""Test""
12
+
},
13
+
{
14
+
""id"":""6"",
15
+
""name"":""TestChild 1""
16
+
}
17
+
]
18
+
}
19
+
}</code></pre>
20
+
<p>We can see that we need to create two classes : ""Test"" and ""User"" since ""users"" property is an array of object with ""id"" and ""name"".</p>
21
+
<p>We can write our Python class along with Its properties as such:/p></p>
22
+
<pre><code>
23
+
from dataclasses import dataclass
24
+
from typing import List
25
+
26
+
@@dataclass
27
+
class User:
28
+
id: str
29
+
name: str
30
+
31
+
@@dataclass
32
+
class Test:
33
+
id: int
34
+
userid: str
35
+
users: List[User]
36
+
</code></pre>
37
+
<p>In Python, It's really easy to load a json string to a dictionary and access the values by calling the dictionary keys. This can be done using</p>
38
+
<p>x = json.loads(my_json_string)</p>
39
+
<p>and accessing the dictionary values by using x[""my_json_key""]</p>
40
+
<p>However, translating these dictionary items to type safe Python properties require a few additional steps that we need to do.</p>
41
+
<h3><strong>2. Map each Json Attribute to a Type Safe Python Property</strong></h3>
42
+
<p>The next step that needs to be done is mapping each Json node and attributes to Python classes and properties. We can do so by creating a static method in our Python classes that's responsible for mapping our dictionary to our Python properties. The Python script will look like this:</p>
43
+
<pre><code>
44
+
from dataclasses import dataclass
45
+
from typing import Any, List
46
+
47
+
@@dataclass
48
+
class User:
49
+
id: str
50
+
name: str
51
+
52
+
@@staticmethod
53
+
def from_dict(obj: Any) -> 'User':
54
+
_id = int(obj.get(""id""))
55
+
_name = str(obj.get(""name""))
56
+
return User(_id, _name)
57
+
58
+
@@dataclass
59
+
class Test:
60
+
id: int
61
+
userid: str
62
+
users: List[User]
63
+
64
+
@@staticmethod
65
+
def from_dict(obj: Any) -> 'Test':
66
+
_id = int(obj.get(""id""))
67
+
_userid = str(obj.get(""userid""))
68
+
_users = [User.from_dict(y) for y in obj.get(""users"")]
69
+
return Test(_id, _userid, _users)
70
+
</code></pre>
71
+
<p>We create a static method called ""from_dic"" and inside this method we created local properties (""_id, _name"") and for each property we are calling our dictionary supplying the keys found in our Json string.</p>
72
+
<p>Note that for Arrays and Lists, what we're doing is we are creating a list of Users and for each user, we are calling the ""from_dict"" method so that the User properties will be mapped as well. This can be seen in the line below: </p>
73
+
<p><code> _users = [User.from_dict(y) for y in obj.get(""users"")]</code> </p>
74
+
<p>Finally, we are returning a mapped object as seen in the last lines of the ""fom_dict"" method:</p>
<h3><strong>3. Wrap your Python Object with a Root Class</strong></h3>
77
+
<p>You can optionally wrap your Python objects with a root class, and this is in case you have multiple classes in the root node of your Json string. </p>
78
+
<p>We can achieve this by adding the below code to your Python Script:</p>
79
+
<pre><code>@@dataclass
80
+
class Root:
81
+
Test: Test
82
+
83
+
@@staticmethod
84
+
def from_dict(obj: Any) -> 'Root':
85
+
_Test = Test.from_dict(obj.get(""Test""))
86
+
return Root(_Test)</code></pre>
87
+
<h3><strong>4. Call the Mapping Function at the Root Class </strong></h3>
88
+
<p>Finally, in order to use our mapping functions, we need to call the Root mapping function ""from_dict"" as such : </p>
89
+
<pre><code># Load the json string to a variable
90
+
output = json.load(open('data.json'))<br />
91
+
# Call the mapping function
92
+
result = Root.from_dict(output)<br />
93
+
# Access your Python properties
94
+
result.Test.userid
95
+
<br /></code></pre>
96
+
<h3><strong>5. Use the Online Tool Above to Generate Python Classes from Json Strings</strong></h3>
97
+
<p>You always use the online tool above to achieve what we did in this example. Just paste your Json in the left text area, hit that convert button, and you will have your python classes with their mappings created automagically !</p>
98
+
<p>The full Python script will look like this:</p>
99
+
<pre><code>
100
+
from dataclasses import dataclass
101
+
from typing import Any, List
102
+
import json
103
+
104
+
@@dataclass
105
+
class User:
106
+
id: str
107
+
name: str
108
+
109
+
@@staticmethod
110
+
def from_dict(obj: Any) -> 'User':
111
+
_id = int(obj.get(""id""))
112
+
_name = str(obj.get(""name""))
113
+
return User(_id, _name)
114
+
115
+
@@dataclass
116
+
class Test:
117
+
id: int
118
+
userid: str
119
+
users: List[User]
120
+
121
+
@@staticmethod
122
+
def from_dict(obj: Any) -> 'Test':
123
+
_id = int(obj.get(""id""))
124
+
_userid = str(obj.get(""userid""))
125
+
_users = [User.from_dict(y) for y in obj.get(""users"")]
0 commit comments