JSON 数据架构 allOf $ref 外部 json 架构文件不起作用

问题描述

我最近开始为我们的一个项目探索 JSON Schema。用例非常简单,经过大量谷歌搜索后,我仍然无法使其工作。其实我在这里有点失落。 .这是我试过的https://json-schema.org/understanding-json-schema/structuring.html

我的common_data_schema.json

{   
 "deFinitions": {
    "sp_common_data": {
      "type": "object","properties": {
        "os_ip": {
          "type": "string","format": "ipv4"
        },"os_user": {
          "type": "string"
        },"os_pwd": {
          "type": "string"
        },"remote_os": {
          "default": "Windows","enum": [
            "Linux","Windows"
          ]
        }
      },"required": [
        "os_ip","os_user","os_pwd","remote_os"
      ]
    }   },"type": "object","properties": {
       "sp_must_data":{ "$ref": "#/deFinitions/sp_common_data" }   
   } 
}

现在我的 server_update.json 架构,我想在其中验证 common_data_schema + new properties

{
  "$schema": "http://json-schema.org/draft-07/schema#","properties": {
      "sp_must_data":{"$ref": "common_data_schema.json#sp_common_data"},"file": {
        "type": "string"
      }
    }
  }

但是当我尝试使用 server_update.json https://python-jsonschema.readthedocs.io/en/stable/ 验证 jsonschema 架构时,它不考虑 $ref 架构 common_data_schema.json 定义

schema loader 逻辑很简单,我所有的架构都驻留在 artifacts 文件夹中

import json
from pathlib import Path

# Location for the test artifacts
artifacts = Path(__file__).parent.parent.joinpath("artifacts").resolve()


def load_schema(filename):
    data = open(Path(artifacts).joinpath(filename),"r").read()
    return json.loads(data) 

下面的 json schema 验证逻辑

from typing import Dict,List
from jsonschema import Draft7Validator,exceptions


def validate(schema: Dict,instance: Dict) -> List[exceptions.ValidationError]:
    """
    Validate the instance using the specified schema

    :param schema: Schema object
    :param instance: instance Object
    :return: List of errors during validation
    """

    validator = Draft7Validator(schema=schema)
    return list(validator.iter_errors(instance))

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)