create Ref-resolver from $ref in jsonschema in python draft7

安稳与你 提交于 2020-06-17 12:56:52

问题


I have json Schema

{
  "$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
}

I am trying to build refresolver for this type of schema where $ref refers to another json file in different directory. Here is the code I tried

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)  

It gives me key error for $ref reference as

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

I think I am missing something while creating refresolver. Any help would be appreciated..


回答1:


please try this: "$ref": "d:/documents/schemaFiles/WorkProduct#/1" if you want to use "1" type defined in WorkProduct.json.

Also see this answer

Hope it can help!



来源:https://stackoverflow.com/questions/60949065/create-ref-resolver-from-ref-in-jsonschema-in-python-draft7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!