【问题标题】:create Ref-resolver from $ref in jsonschema in python draft7在 python Draft7 的 jsonschema 中从 $ref 创建 Ref-resolver
【发布时间】:2020-03-31 11:03:31
【问题描述】:

我有 json 架构

{
  "$id": "d:/documents/schemaFiles/WLWorkProduct/1",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "WLWorkProduct",
  "description": "",
  "type": "object",
  "properties": {
    "RID": {
      "description": "resource type.",
      "type": "string"
    },
    "Data": {
      "type": "object",
      "properties": {
        "IndividualTypeProperties": {
          "allOf": [
            {
              "$ref": "d:/documents/schemaFiles/WorkProduct/1"
            },
            {
              "type": "object",
              "properties": {
                "WID": {
                  "type": "string",
                  "description": "WID"
                }
              }
            }
          ]
        }
      }
    }
  },
  "additionalProperties": false
}

我正在尝试为这种模式构建 refresolver,其中 $ref 引用不同目录中的另一个 json 文件。这是我尝试过的代码

import os
import pathlib
import json
from jsonschema import Draft7Validator, FormatChecker, ValidationError, SchemaError, validate, RefResolver, exceptions

BASE_DIR='d:/documents/schemaFiles'
schemaPath='d:/documents/schemaFiles'
json_file='d:/documents/results/OutawsLog.json' #API output

def _validate(schema_search_path, json_data, schema_id):
    """
    load the json file and validate against loaded schema
    """
    try:
        schemastore = {}
        fnames=[]
        for roots, _, files in os.walk(schema_search_path):
            for f in files:
                if f.endswith('.json'):
                    fnames.append(os.path.join(roots, f))

        for fname in fnames:
            with open(fname, "r") as schema_fd:
                schema = json.load(schema_fd)
                if "$id" in schema:
                    print("schema[$id] : ", schema["$id"])
                    schemastore[schema["$id"]] = schema

        test_schema_id='d:/documents/schemaFiles/WLWorkProduct/1'
        schema = schemastore.get(test_schema_id)
        Draft7Validator(schema)
        resolver = RefResolver(BASE_DIR, "file://{0}".format(os.path.join(BASE_DIR, '/WLWorkProduct.json')), schema, schemastore)
        try:
            v=Draft7Validator(schema, resolver=resolver).iter_errors(json_data)
            print("v : ", v)
            for error in v:
                print(error.message)
        except ValidationError as e:
            print(e)
    except Exception as error:
        # handle validation error 
        print(error)
    except SchemaError as error:
        print(error)
        return False


def getData(jsonFile):
    with open(jsonFile) as fr:
        dt=json.loads(fr.read())['results']['results']
        return dt

json_dt=getData(json_file)
for jd in json_dt[:1]:
    print(type(jd))       
    _validate(schemaPath, jd, 1)  

它给了我 $ref 参考的关键错误

  1. jsonschema.exceptions.RefResolutionError:
  2. KeyError: 'd:/documents/schemaFiles/WorkProduct/1'

我想我在创建 refresolver 时遗漏了一些东西。任何帮助将不胜感激..

【问题讨论】:

    标签: python-3.x jsonschema json-schema-validator


    【解决方案1】:

    如果您想使用 WorkProduct.json 中定义的“1”类型,请尝试以下操作:“$ref”:“d:/documents/schemaFiles/WorkProduct#/1”。

    Also see this answer

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多