pythonvalidationmarshmallow

How to validate a JSON list of dictionaries using Marshmallow in Python?


How can I validate nestes json data using Marshmallow?

This was I came up with, currently I get:

{'_schema': ['Invalid input type.']} note sure why.

from marshmallow import Schema, fields, validate 

class AuthUserSchema(Schema):
    user = fields.String()
    password = fields.String()
    enabled = fields.Boolean()

class AuthDataSchema(Schema):
    data = fields.List(fields.Nested(AuthUserSchema))

data = [
    {
        "enabled": True,
        "password": "6e5b5410415bde",
        "user": "admin"
    },
    {
        "enabled": True,
        "password": "4e5b5410415bde",
        "user": "guest"
    },
]

schema = AuthDataSchema()
errors = schema.validate(data)
print(errors)

Solution

  • I think this line is causing issue -

    errors = schema.validate(data)
    

    Just modify it to -

    errors = schema.validate({"data":data})
    

    And now you can directly use fields.Nested -

    data = fields.Nested(AuthUserSchema, many=True)