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

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

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

问题

以下是您要翻译的内容:

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

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

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

  1. from marshmallow import Schema, fields, validate
  2. class AuthUserSchema(Schema):
  3. user = fields.String()
  4. password = fields.String()
  5. enabled = fields.Boolean()
  6. class AuthDataSchema(Schema):
  7. data = fields.List(fields.Nested(AuthUserSchema))
  8. data = [
  9. {
  10. "enabled": True,
  11. "password": "6e5b5410415bde",
  12. "user": "admin"
  13. },
  14. {
  15. "enabled": True,
  16. "password": "4e5b5410415bde",
  17. "user": "guest"
  18. },
  19. ]
  20. schema = AuthDataSchema()
  21. errors = schema.validate(data)
  22. 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.

  1. from marshmallow import Schema, fields, validate
  2. class AuthUserSchema(Schema):
  3. user = fields.String()
  4. password = fields.String()
  5. enabled = fields.Boolean()
  6. class AuthDataSchema(Schema):
  7. data = fields.List(fields.Nested(AuthUserSchema))
  8. data = [
  9. {
  10. "enabled": True,
  11. "password": "6e5b5410415bde",
  12. "user": "admin"
  13. },
  14. {
  15. "enabled": True,
  16. "password": "4e5b5410415bde",
  17. "user": "guest"
  18. },
  19. ]
  20. schema = AuthDataSchema()
  21. errors = schema.validate(data)
  22. 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 -

  1. errors = schema.validate(data)

Just modify it to -

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

And now you can directly use fields.Nested -

  1. 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:

确定