使用相同的JSON模式文件验证多个子模式

2024-04-30 06:30:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON模式,我希望在其中定义我项目的所有对象我希望能够通过这个JSON模式(使用“jsonschema”python库)验证我的所有对象。。为了避免重复,我不想为每个对象创建一个模式文件

考虑下面的说明性玩具实例(^ {CD1>}):

{
"$schema":"https://json-schema.org/draft/2020-12/schema", 
"$id":"https://example.com/toy-example.json",
"title": "JSON Schema",
"description": "JSON Schema deifning objects a,b and c",
"type": "object",
"$defs":{
    "a": {
        "$id": "#a",
        "type": "object",
        "properties": {
            "c_array": {
                "type": "array",
                "items": {
                    "$ref": "#/$defs/c"
                }
            }
        },
        "required": ["c_array"]
    },
    "b": {
        "$id": "#b",
        "type": "object",
        "properties": {
            "c": {"ref": "#/$defs/c"}
            },
        "required": ["c"]
    },
    "c": {
        "$id": "#c",
        "type": "number",
        "minimum": 0
    }
},
"allOf": [{"$ref": "#/$defs/a"}]
}

以下代码用于验证“a”对象(由于底部添加了“allOf”指令):

import jsonschema, json
with open("toy-schema.json", "r") as f: schema = json.load(f)

a = {"c_array": [1,2,3]}
jsonschema.validate(a, schema) ## is valid, correctly stays silent
a = {"c_array": [-1,2,3]}
jsonschema.validate(a, schema) ## is invalid (-1 < 0), correctly raises ValidationError

我还希望能够验证对象“b”,理想情况下使用如下语法:

import jsonschema, json
with open("toy-schema.json", "r") as f: schema = json.load(f)

b = {"c": 1}
jsonschema.validate(b, schema, "/$defs/#b") ## valid
b = {"c": -1}
jsonschema.validate(b, schema, "/$defs/#b") ## invalid
  • 可以这样做吗?即,指向架构的特定部分进行验证(从而保留对同一架构中其他对象定义的引用)
  • 这是可取的还是反模式?在这种情况下,对于我的问题,哪个JSON模式结构更可取

我相信这样做可以避免任何模式定义的重复


Tags: 对象refidjson定义objectschematype