简体   繁体   English

Python jsonschema 未验证 ref 文件中的必需属性

[英]Python jsonschema not validating on required property from ref file

I am trying to validate a JSON schema using python jsonschema using a "$ref" that points to an external file.我正在尝试使用 python jsonschema 使用指向外部文件的“$ref”来验证 JSON 模式。 My issue is that the "required" properties in the external file are not failing validation when they are not present in the request.我的问题是外部文件中的“必需”属性在请求中不存在时不会通过验证。 Based on the info below, I would have expected my request to fail because 'ofld2' is missing.根据下面的信息,我预计我的请求会失败,因为缺少“ofld2”。 If I omit any of the required fields from the parent schema, it fails properly.如果我从父模式中省略任何必填字段,它会正确失败。 Any help/guidance would be greatly appreciated.任何帮助/指导将不胜感激。

Parent Json File: test_refs.json:父 Json 文件:test_refs.json:

{
    "test_refs":{
            "schema": {
                "allOf": [
                    {
                    "type": "object",
                    "properties": {
                        "fld1": {
                            "type": "string"
                        },
                        "fld2": {
                            "type": "string"
                        },
                        "fld3": {
                            "type": "string"
                        },
                        "ref1": { 
                            "$ref":"myref.json"
                        }
                    },
                    "required": ["fld1", "fld2", "fld3", "ref1"]
                    }
                ]
            }
        }
}

Reference Json file:参考Json文件:

{
    "myrefs": {
        "schema": {
            "$schema": "http://json-schema.org/draft-04/schema#",
            "id":"myref",
            "type": "object",
            "properties": {
                "ofld1": {"type": "string"},
                "ofld2": {"type": "string"},
                "ofld3": {"type": "string"}
            },
            "required": ["ofld1", "ofld2"]
        }
    }
}

My validation logic:我的验证逻辑:

 req_schema = resource_config.get("schema", {})
 schema = jsonschema.Draft4Validator(req_schema)
 try:
    json_content = jsonref.loads(content)
 except Exception as error:
    is_valid = False
    log.error(error)
    myerrors.append("EXCEPTION Error: invalid message payload.")

Request Data:请求数据:

{'fld1': '10.0', 'fld2': '10.0', 'fld3': 'test', 'ref1': {'ofld1': 'test 1', 'ofld3': 'test  3'}}

Schema:架构:

{
    'schema': {
    'allOf': [
        {'type': 'object', 
        'properties': 
            {'fld1': {'type': 'string'}, 
            'fld2': {'type': 'string'},
            'fld3': {'type': 'string'}, 
            'ref1': {
                'myrefs': {
                    'schema': {
                        '$schema': 'http://json-schema.org/draft-04/schema#', 
                        'id': 'myref', 
                        'type': 'object', 
                        'properties': {
                            'ofld1': {'type': 'string'}, 
                            'ofld2': {'type': 'string'}, 
                            'ofld3': {'type': 'string'}
                         }, 
                        'required': ['ofld1', 'ofld2']}
                        }
                    }
                }, 
            'required': ['fld1', 'fld2', 'fld3', 'ref1']}
            ]
        }, 
        'resolver': <jsonschema.validators.    RefResolver object at 0xb0e4526c>, 'format_checker': None}

UPDATE: Here is a test script that produces this output using the files:更新:这是一个使用文件生成此输出的测试脚本:

import json
import jsonref
import jsonschema
import logging
from os.path import dirname
from jsonschema import validate



def read_json_file(file_path):
    """Reads the file at the file_path and returns the contents.
        Returns:
            json_content: Contents of the json file

        """
    try:
        json_content_file = open(file_path, 'r')
    except IOError as error:
        print(error)

    else:
        try:
            base_path = dirname(file_path)
            base_uri = 'file://{}/'.format(base_path)
            json_schema = jsonref.load(json_content_file, base_uri=base_uri, jsonschema=True)
        except (ValueError, KeyError) as error:
            print(file_path)
            print(error)

        json_content_file.close()

    return json_schema

def validate_json_file(json_data):
    req_schema = read_json_file('/path/to/json/files/test_refs.json')
    print("SCHEMA --> "+str(req_schema))
    try:
        validate(instance=json_data, schema=req_schema)
    except jsonschema.exceptions.ValidationError as err:
        print(err)
        err = "Given JSON data is InValid"
        return False, err

    message = "Given JSON data is Valid"
    return True, message


jsonData = jsonref.loads('{"fld1": "10.0", "fld2": "10.0", "fld3": "test", "ref1": {"ofld1": "test 1", "ofld3": "test  3"}}')
is_valid, msg = validate_json_file(jsonData)
print(msg)

Your schema is malformed.您的架构格式不正确。 Everything under /schema/allOf/0/properties/ref1 is not a valid schema, so it is all ignored. /schema/allOf/0/properties/ref1 下的所有内容都不是有效的架构,因此将全部忽略。 You should lift the embedded schema up multiple levels and place it right under ref1.您应该将嵌入式架构提升多个级别并将其放在 ref1 的正下方。

The first two schemas you included aren't referenced anywhere;您包含的前两个模式在任何地方都没有引用; are they just intended to be copies of the schema you created where everything is embedded?它们只是为了成为您创建的嵌入所有内容的架构的副本吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM