发布于 2025-01-27 22:02:58 字数 4363 浏览 2 评论 0原文

我正在尝试使用Python JSonschema使用指向外部文件的“ $ REF”来验证JSON模式。我的问题是,当请求中不存在时,外部文件中的“必需”属性不会失败。 基于下面的信息,我希望我的请求失败,因为“ ofld2”缺少。如果我省略了父模式的任何必需字段,则它会正确地失败。 任何帮助/指导将不胜感激。

父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"]
                    }
                ]
            }
        }
}

参考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"]
        }
    }
}

我的验证逻辑:

 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.")

请求数据:

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

架构:

{
    '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}

更新: 这是一个测试脚本,可使用文件产生此输出:

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)

I am trying to validate a JSON schema using python jsonschema using a "$ref" that points to an external file. 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. 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:

{
    "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:

{
    "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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

司马昭之心 2025-02-03 22:02:58

您的模式畸形。 /schema/allof/0/properties/ref1下的所有内容都不是有效的架构,因此都被忽略了。您应该将嵌入式模式提升到多个级别,然后将其放在参考文献1下。

您随身携带的前两个模式在任何地方都没有引用;它们是否只是打算是您创建的所有内容的模式的副本?

Your schema is malformed. Everything under /schema/allOf/0/properties/ref1 is not a valid schema, so it is all ignored. You should lift the embedded schema up multiple levels and place it right under 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文