Search code examples
pythonmarshmallow

Validation of nested dictionary's value type


I check the python data in marshmallow, the food field is a list, and the list stores the dict. I can only do this step. In fact, I want to verify that the value in the dict is int instead of string. How should I modify my code?

from marshmallow import Schema, fields, pprint

class UserSchema(Schema):
    name = fields.Str()
    food = fields.List(fields.Dict)

user_data = {
    "name": "Ken",
    "food": [{'apple': 2, 'banana': 4}, {'apple': '2', 'banana': '4'}]
}

result = UserSchema().load(user_data)
pprint(result)

Solution

  • Code below should validate your data pattern.
    Look at comments in code, it's simple explanation.

    from marshmallow import ValidationError, Schema, fields, pprint # Added `ValidationError`.
    
    user_data = {
        "name": "Ken",
        "food": [
            {'apple': 2, 'banana': 4}, 
            {'apple': '2', 'banana': '4'}
        ]
    } # `user_data` is as is without changes.
    
    # New function for validation your dictionary.
    def validate_value_type(dict):
        for key in dict:
            if type(dict[key]) is not int:
                raise ValidationError(f'Type of {key}\'s value is not Integer')
    
    # `UserSchema` class with changes.
    class UserSchema(Schema):
        name = fields.Str()
        food = fields.List(fields.Dict(validate=validate_value_type)) # Added validation function.
    
    # Wrapped `load` in `try/catch`.
    try:
        UserSchema().load(user_data)
    except ValidationError as err:
        pprint(err.messages)
    

    Above code output:

    {'food': {1: ["Type of apple's value is not Integer"]}}