Quantcast
Viewing latest article 23
Browse Latest Browse All 51036

Deserialize Complex Json into object using Marshmallow

Hello, I am trying to deserialize json into an object that has nested objects within it.

I am able to deserialize the json into the root level object and the rest of the objects do have values, but I can't go further into the structure.

For example
class CustomerDTO(BaseDTO)
    first_name: str = fields.Str(required=True)
    last_name: str = fields.Str(required=True)
    address: AddressDTO = fields.Nested(AddressDTOSchema, required=True)
 
class CustomerDTOSchema(Schema, CustomerDTO)
    pass
 
class AddressDTO(BaseDTO)
    street_name_one: str = fields.Str(required=True)
    street_name_two: str = fields.Str(required=False)
    city: str = fields.Str(required=True)
    state: str = fields.Str(required=True)
    zip_code: str = fields.Str(required=True)
 
class AddressDTOSchema(Schema, AddressDTO)
    pass



If I run something like

customer_data = request.get_json()
customer_dto_schema = CustomerSchema().load(customer_data)
customer_dto = CustomerDTO(**customer_dto_schema)
 
print(customer_dto) #this works fine
print(customer_dto.first_name) # this works fine
print(customer_dto.address) # this works fine
print(custome_dto.address.street_name_one) # I get an error here -> 'dict' object has no attribute 'street_name_one'



The request.get_json() returns something like this
{
  'first_name': 'John',
  'last_name': 'Doe',
  'address': {
    'street_name_one': '123 Main Street',
    'street_name_two': 'Apt 123',
    'city': 'TestCity',
    'state': 'TX',
    'zip_code': '12345'
   }
}



How can I have this cascade down into the nested objects?

Viewing latest article 23
Browse Latest Browse All 51036

Trending Articles