Search code examples
json.netjsonschema

JSON schema $id scoping discrepencies


Given the following schema definition:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://fobar.json",
  "type": "object",
  "$defs": {
    "one": {
      "$id": "/one",
      "type": "string"
    },
    "two": {
      "$id": "a/sub/schema.json",
      "properties": {
        "one": {
          "$id": "/one",
          "type": "integer"
        }
      }
    }
  },
  "properties": {
    "a": {
      "$ref": "one"
    }
  }
}

When I use ajv to compile this, I get an error "http://foobar.json/one" resolves to more than one schema Which I believe to be the correct error. https://www.jsonschemavalidator.net/ however, fails to give an error on this. It will give a warning, if I add, "b": {"$ref": "a/sub/schema.json"} after the a property


Solution

  • It's because in http://fobar.json, fobar.json is the domain. Paths are resolved on the domain.

    Additionally, the slash on /one means "start from the root of the domain."

    • /one is a path on the fobar.json domain to give you http://fobar.json/one (for both cases, causing your error)
    • a/sub/schema.json gives http://fobar.json/a/sub/schema.json

    If you want the /one nested under the two property to resolve to http://fobar.json/a/sub/one (which is what it sounds like you want), you'll need to lose the slash and just use one for the $id there.