【问题标题】:jsonschema library -- schema is not valid?jsonschema 库——模式无效?
【发布时间】:2017-11-02 02:05:36
【问题描述】:

我在我的 Django 应用程序中使用 jsonschema 库 (http://python-jsonschema.readthedocs.io/en/latest/validate/) 进行服务器端验证,并尝试使用提供的模式对 JSON 进行服务器端验证。但是,我收到架构“在任何给定架构下都无效”的错误消息。

这是我的架构(它是类的“schema”属性的“scores_ap”属性):

class JSONListFieldSchemas:
    """
    Schemas for all the JSON List Fields.
    Each key represents the field name.
    """
    schema = {
        "scores_ap": {
            "$schema": "http://json-schema.org/draft-06/schema#",
            "title": "AP Scores",
            "type": "array",
            "items": {
                "type": "object",
                        "properties": {
                        "exam": {
                            "type": "string"
                        },
                        "score": {
                            "type": "integer",
                            "minimum": "1",
                            "maximum": "5",
                            "required": False
                        }
                        }
            }
        }
}

我收到此错误:

{'type': 'object', 'properties': {'score': {'minimum': '1', 'type': 'integer', 'ma
ximum': '5', 'required': False}, 'exam': {'type': 'string'}}} is not valid under a
ny of the given schemas

Failed validating u'anyOf' in schema[u'properties'][u'items']:
    {u'anyOf': [{u'$ref': u'#'}, {u'$ref': u'#/definitions/schemaArray'}],
     u'default': {}}

On instance[u'items']:
    {'properties': {'exam': {'type': 'string'},
                    'score': {'maximum': '5',
                              'minimum': '1',
                              'required': False,
                              'type': 'integer'}},
     'type': 'object'}

我使用的架构如下:

from jsonschema import validate
from .schemas import JSONListFieldSchemas
raw_value = [{"score": 1, "exam": "a"}]
validate(raw_value, JSONListFieldSchemas.schema['scores_ap'])

【问题讨论】:

    标签: python json django validation jsonschema


    【解决方案1】:

    从草案 4 开始,“必需”应该是一个数组而不是布尔值。 “最大值”和“最小值”也应该是整数,而不是字符串。

    试试这样:

    {
      "$schema": "http://json-schema.org/draft-06/schema#",
      "title": "AP Scores",
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "exam": {
            "type": "string"
          },
          "score": {
            "type": "integer",
            "minimum": 1,
            "maximum": 5
          }
        },
        "required": [
          "exam"
        ]
      }
    }
    

    【讨论】:

    • 谢谢!我的代码中的数据是一个数组——还是我声明它错了?
    • 是的,对不起,我的错误,没有仔细看。我会更新我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多