Python Forum

Full Version: Deserialize Complex Json to object using Marshmallow
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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'
How can I have this cascade down into the nested objects?
Then you have to inspect what request.get_json() gives as a result.
(Dec-09-2021, 06:23 PM)ibreeden Wrote: [ -> ]Then you have to inspect what request.get_json() gives as a result.

The request_json gives me 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'
   }
}