【问题标题】:Validate list of dicts using cerberus使用 cerberus 验证字典列表
【发布时间】:2021-08-23 07:22:54
【问题描述】:

开始使用 cerberus 进行合约测试。

当我们得到基于 dict 的 JSON 结构时,它可以完美运行,例如:

{'results': [{"key": "value"}, {"key": "value"}, {"key":"value}]}

但是当响应只是一个字典列表时,一切都会变糟,例如:

[{"key": "value"}, {"key": "value"}, {"key":"value}]

我面临的基本错误是:

cerberus.validator.DocumentError: '[{'id': 'XXX', 'is_supported': True}]' is not a document, must be a dict

指定顶级类型:模式中的“列表”没有帮助,返回模式错误:

cerberus.schema.SchemaError: {'type': ['must be of dict type']}

天真的解决方案只是通过列表并验证里面的所有实体。 但看起来应该有更合适的方法来做到这一点。

据我所知(正如谷歌所说),顶级数组是一个有效的 JSON 结构,所以应该有一种方法来正确验证它,不是吗?

【问题讨论】:

    标签: python cerberus


    【解决方案1】:

    我更愿意将此作为评论发布,但我没有声誉。尽管如此,这里还是有人问了同样的问题:https://github.com/pyeve/cerberus/issues/220

    一种解决方案是编写Validator subclass,另一种是使用cerberus-list-schema,它显然基于Cerberus,但也支持列表和数组模式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      相关资源
      最近更新 更多