2

I have been trying so hard to figure out how to get a schema that is nested in a definition with a $ref. If I hard code the jsonschema object I have no problems whatsoever, however I need to use a nested schema and I don't know what schema= in validate(json{"name": "lucky","uid": -1, schema='what do I put here to reference the ref schema?')?

Here is the code that I'm using to isolate and test the functionality.

import jsonschema
from jsonschema import validate

schemas = {
    "$schema": "http://json-schema.org/draft-07/schema#",
    # "$id": "http://example.com",
    "definitions": {
        # base schema
        "uid": {
            "$id": "#uid",
            "type": "integer",
            "minimum": 1
        },
        # extended schema
        "user_record_with_ref": {
            "$id": "#user_record_with_ref",
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "uid": {
                    "allOf": [{"$ref": "#uid"}]
                }
            }
        }
    }
}

user_record_no_ref = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "uid": {"type": "integer", "minimum": 1}
    }
}

# I'd prefer that validation fails to prove the I am validating properly.
user_record_object = {"name": "lucky", "uid": -1}


# It is simple to validate a schema that does not use references.
def test_no_ref():
    try:
        validate(instance=user_record_object, schema=user_record_no_ref)
    except jsonschema.exceptions.ValidationError as e:
        return f'JSON Error {e}', 400

    return 'yay no problems'


def test_with_ref():
    try:
        # I want to use 'schema=user_record_with_ref' but I don't know how to access it.
        validate(instance=user_record_object, schema="")
    except jsonschema.exceptions.ValidationError as e:
        return f'JSON Error {e}', 400

    return 'yay no problems'

# Testing
print(test_no_ref())

print(test_with_ref())

I have tried schemas['definitions']['user_record_with_ref'] but that doesn't work at all. Maybe this requires a ref resolver? I don't think it does though since the subschemas are within a single schema block. Any help would be so appreciated.

0 Answers0