Search code examples
validationjsonschema

Reference subkeys from external, remote JSON schema


I have started working with JSON Schema in a project of mine. I am still having issues understanding how $id and $ref work together, and where tools, $id, base_uri, etc. com together. Here's a scenario:

I have my schema defined in a file schema.json. This file is hosted on my website https://example.com/schema.json. The $id of the schema is https://example.com/schema/. The $schema is "http://json-schema.org/draft-07/schema".

I can use this schema in the validator at https://www.jsonschemavalidator.net/ by giving it a schema where the URL is referenced, and validation works (invalid instances fail, etc.).

{
  "$ref": "https://example.com/schema.json"
}

I can resolve subkeys by using "$ref": "https://example.com/schema.json#/properties/subkey". "$ref": "https://example.com/schema#/properties/subkey" doesn't resolve, perhaps because it's not findable in a schema store?

So now, if I wanted this to work - "$ref": "https://example.com/schema#/properties/subkey", would I have to rename the file to simply schema? Or is there another way how this would work?


Solution

  • "schema" and "schema.json" point to different files, so you either need to rename the file to match the uri in the $ref, or change the $ref to refer to the correct filename.

    This guide may help: Structuring a complex schema