python-jsonschema / jsonschema

An implementation of the JSON Schema specification for Python
https://python-jsonschema.readthedocs.io
MIT License
4.6k stars 580 forks source link

Validation starting from sub-definition #1186

Closed eirnym closed 11 months ago

eirnym commented 11 months ago

Hi,

I have a Json Schema in a single file with multiple objects. root object is not defined and I have only objects in $defs. Could you please suggest how to validate a json against these defintions? E.g. from schema below, how to validate an object against schema which would "start" at #/$defs/Object1VariantA or #/$defs/Object1VariantB or #/$defs/Object1VariantC?

From my point of view nothing wrong could happen if there's a way to start validation from a specific definition, not from the top. This is not a canonical way to do that, but I haven't found anything in json schema RFCs which tells, that validation should start only from the top (#/ reference).

I can't alter the schema, or create multiple files around. Schema below is a very small part of the original one to show the relevant example.

Schema example (in yaml format, as it's way easier for me to write it):

$schema: "https://json-schema.org/draft/2020-12/schema"

$defs:
  IDType:
    type: string
    pattern: '[a-z][a-z0-9]{10}'

  Object1Common:
    type: object
    properties:
      title:
        type: string
        maxLength: 200
      description:
        type: string

  Object1VariantA:
    type: object
    allOf:
      - $ref: "#/$defs/Object1Common"
    required:
      - title

  Object1VariantB:
    type: object
    properties:
      id:
        $ref: "#/$defs/IDType"
    allOf:
      - $ref: "#/$defs/Object1Common"
    required:
      - id
      - title

  Object1VariantC:
    type: object
    allOf:
      - $ref: "#/$defs/Object1Common"