How to set up local file references in python-jsonschema document?

后端 未结 5 2045
失恋的感觉
失恋的感觉 2021-01-02 08:28

I have a set of jsonschema compliant documents. Some documents contain references to other documents (via the $ref attribute). I do not wish to host these docum

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 09:24

    I had the hardest time figuring out how to do resolve against a set of schemas that $ref each other (I am new to JSON Schemas). It turns out the key is to create the RefResolver with a store that is a dict which maps from url to schema. Building on @devin-p's answer:

    import json
    
    from jsonschema import RefResolver, Draft7Validator
    
    base = """
    {
      "$id": "base.schema.json",
      "type": "object",
      "properties": {
        "prop": {
          "type": "string"
        }
      },
      "required": ["prop"]
    }
    """
    
    extend = """
    {  
      "$id": "extend.schema.json",
      "allOf": [
        {"$ref": "base.schema.json#"},
        {
          "properties": {
            "extra": {
              "type": "boolean"
            }
          },
        "required": ["extra"]
        }
      ]
    }
    """
    
    extend_extend = """
    {
      "$id": "extend_extend.schema.json",
      "allOf": [
        {"$ref": "extend.schema.json#"},
        {
          "properties": {
            "extra2": {
              "type": "boolean"
            }
          },
        "required": ["extra2"]
        }
      ]
    }
    """
    
    data = """
    {
    "prop": "This is the property string",
    "extra": true,
    "extra2": false
    }
    """
    
    schema = json.loads(base)
    extendedSchema = json.loads(extend)
    extendedExtendSchema = json.loads(extend_extend)
    schema_store = {
        schema['$id'] : schema,
        extendedSchema['$id'] : extendedSchema,
        extendedExtendSchema['$id'] : extendedExtendSchema,
    }
    
    
    resolver = RefResolver.from_schema(schema, store=schema_store)
    validator = Draft7Validator(extendedExtendSchema, resolver=resolver)
    
    jsonData = json.loads(data)
    validator.validate(jsonData)
    

    The above was built with jsonschema==3.2.0.

提交回复
热议问题