'Parse from json to complex python object not resolving inner types. Inner types are always dict

I am trying to parse from a json to a complex python object and then use that python object.

Since the inner object is being resolved to type dict I having issues.

Error

Traceback (most recent call last):
   File "/Users/jerin.joseph/Documents/Jerin/Samples/python_samples/deserialization.py", line 41, in <module>
     print(decoded_team.students[0].first_name)
 AttributeError: 'dict' object has no attribute 'first_name'
from typing import List
import json
 
 
class Student(object):
    def __init__(self, first_name: str, last_name: str):
        self.first_name = first_name
        self.last_name = last_name
 
 
class Team(object):
    def __init__(self, students: List[Student]):
        self.students = students
 

json_data_str = '''
{
    "students": [
        {
            "first_name": "Jerin",
            "last_name": "Joseph"
        },
        {
            "first_name": "Mathew",
            "last_name": "Paul"
        }
    ]
}
'''
 

# Deserialization
decoded_team = Team(**json.loads(json_data_str))
# Prints correct JSON
print(decoded_team)


print(f"Decoded Team {type(decoded_team)}")  #<class '__main__.Team'>
print(f"Decoded Student {type(decoded_team.students[0])}") # <class 'dict'>

print(decoded_team.students[0].first_name)
# Traceback (most recent call last):
#   File "/Users/jerin.joseph/Documents/Jerin/Samples/python_samples/deserialization.py", line 41, in <module>
#     print(decoded_team.students[0].first_name)
# AttributeError: 'dict' object has no attribute 'first_name'


Please note: The object is complex and has more than 5 levels, and I will not be able to access the set values like

decoded_team.students[0]['first_name']

We can use Simplenamespace to correct the access

decoded_team = json.loads(json_data_str, object_hook=lambda d: SimpleNamespace(**d))

but that will make the types of classes as types.SimpleNamespace, but I need it to be Team and Student.

Is there a way to correctly and recursively create correct types of complex python objects



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source