如何使用Python中的Marshmallow验证JSON字典列表?

huangapple go评论62阅读模式
英文:

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

问题

以下是您要翻译的内容:

如何使用Marshmallow验证嵌套的JSON数据?

这是我想出来的方法,目前我得到的结果是:

{'_schema': ['无效的输入类型。']}
不确定为什么。

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)
英文:

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)

答案1

得分: 1

I think this line is causing issue -

这一行可能引起问题 -

errors = schema.validate(data)

只需将其修改为 -

只需将其修改为 -

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

And now you can directly use fields.Nested -

现在你可以直接使用 fields.Nested -

英文:

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)

huangapple
  • 本文由 发表于 2023年5月11日 14:26:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224705.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定