需要 json 模式验证 Python 中的详细错误

问题描述 投票:0回答:1

我有以下 json 模式,我想使用 python 的库根据给定模式验证输入 json,它使用的是 Draft-08 版本,即 2019-09。所以我尝试使用下面的代码进行相同的操作,但它没有给出详细的错误,例如。在提供的示例中,重新发送的输入是布尔类型,因此它应该给出错误,因为这不是布尔类型,但代码给出的错误为 <[{'entityType': 'default', 'function': '01', 'resending': 'False', 'afdDefinitionName': 'example', 'originalMessageId': '12345'}] does not contain items matching the given schema>

架构:

{
    "$schema": "http://json-schema.org/draft/2019-09/schema#",
    "description": "my schema",
    "definitions": {
      "BCCI": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "entityType": {
            "description": "",
            "type": "string",
            "const": "default"
          },
          "function": {
            "description": "",
            "codelistName": "ADNFUN",
            "type": "string",
            "oneOf": [
              {
                "const": "01"
              },
              {
                "const": "02"
              },
              {
                "const": "09"
              },
              {
                "const": "54"
              }
            ]
          },
          "resending": {
            "description": "",
            "type": "boolean"
          },
          "afdDefinitionName": {
            "description": "",
            "customDescription": "",
            "type": "string"
          },
          "originalMessageId": {
            "description": "",
            "customDescription": "",
            "type": "string"
          }
        },
        "required": [
          "entityType",
          "function",
          "afdDefinitionName"
        ]
      }
    },
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "BCCI": {
        "type": "array",
        "uniqueItems": true,
        "allOf": [
          {
            "minContains": 1,
            "maxContains": 1,
            "contains": {
              "$ref": "#/definitions/BCCI"
            }
          }
        ]
      }
    },
    "required": [
      "BCCI"
    ]
  }

json 输入:

{
    "BCCI": [
        {
            "entityType": "default",
            "function": "01",
            "resending": "false",
            "afdDefinitionName": "example",
            "originalMessageId": "12345"
        }
    ]
}

使用的代码:

import json
import jsonschema
from jsonschema import validate, validators, Draft7Validator, Draft201909Validator, Draft202012Validator
from jsonschema.exceptions import ValidationError

json_file = 'path to json instance'
json_schema_file = 'path to json schema instance'

with open(json_file) as f:
    document = json.load(f)

with open(json_schema_file) as f:
    schema = json.load(f)

errors = []
try:
    validate(instance=document, schema=schema)
except jsonschema.exceptions.ValidationError as e:
    print("----------------------------------------------------------")
    print(e)
    print("----------------------------------------------------------")
    
    print(f"Error message: {e.message}")
    print(f"Error tag: {e.json_path}")
    print(f"Error tag: {list(e.path)}")
    print(f"Definition: {e.validator}")

输出:

----------------------------------------------------------
[{'entityType': 'default', 'function': '01', 'resending': 'false', 'afdDefinitionName': 'example', 'originalMessageId': '12345'}] does not contain items matching the given schema

Failed validating 'contains' in schema['properties']['BCCI']['allOf'][0]:
    {'contains': {'$ref': '#/definitions/BCCI'},
     'maxContains': 1,
     'minContains': 1}

On instance['BCCI']:
    [{'afdDefinitionName': 'example',
      'entityType': 'default',
      'function': '01',
      'originalMessageId': '12345',
      'resending': 'false'}]
----------------------------------------------------------
Error message: [{'entityType': 'default', 'function': '01', 'resending': 'false', 'afdDefinitionName': 'example', 'originalMessageId': '12345'}] does not contain items matching the given schema
Error tag: $.BCCI
Error tag: ['BCCI']
Definition: contains

它应该打印有关布尔问题的信息,或者输入 json 是否存在任何其他问题,但它不会详细给出错误。

python json jsonschema json-schema-validator
1个回答
0
投票

问题在于 Draft-08 版本中使用的关键字,这就是为什么它没有给出正确的详细错误,请在您的架构中使用 Items/minItems/maxItems 而不是 contains/minContains/maxContains 那么您的代码将起作用,下面是我正在使用的更新代码给出了一个特定 json 实例的所有错误的详细错误信息。

import json
from jsonschema import  Draft201909Validator

json_file = 'test.json'
json_schema_file = 'test_schema.json'

with open(json_file) as f:
    document = json.load(f)

with open(json_schema_file) as f:
    schema = json.load(f)

v = Draft201909Validator(schema)

for rec in document:
    temp = rec.get("error", [])
    errors = sorted(v.iter_errors(rec), key=lambda e: e.path)
    for error in errors:
        print("---------------------------------------")
        print("json_path list:", list(error.path))
        print("error_message:", error.message)
        

更新了 json 输入架构:

{
    "$schema": "http://json-schema.org/draft/2019-09/schema#",
    "description": "my schema",
    "definitions": {
      "BCCI": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "entityType": {
            "description": "",
            "type": "string",
            "const": "default"
          },
          "function": {
            "description": "",
            "codelistName": "XXXXXX",
            "type": "string",
            "oneOf": [
              {
                "const": "01"
              },
              {
                "const": "02"
              },
              {
                "const": "09"
              },
              {
                "const": "54"
              }
            ]
          },
          "resending": {
            "description": "",
            "type": "boolean"
          },
          "afdDefinitionName": {
            "description": "",
            "customDescription": "",
            "type": "string"
          },
          "originalMessageId": {
            "description": "",
            "customDescription": "",
            "type": "string"
          }
        },
        "required": [
          "entityType",
          "function",
          "afdDefinitionName"
        ]
      }
    },
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "BCCI": {
        "type": "array",
        "uniqueItems": true,
        "items": {
            "$ref": "#/definitions/BCCI"
          },
          "minItems": 1,
          "maxItems": 1
      }
    },
    "required": [
      "BCCI"
    ]
  }

© www.soinside.com 2019 - 2024. All rights reserved.