Velmurugan K
Velmurugan K

Reputation: 21

Referring Schema name from JSON document

I'm validation my JSON document with JSON schema by java. All JSON document structures will not be same. So, we decided to send the JSON document with schema version/name. Is there any way to validate the JSON document by referring the schema name in same document. JSON doc structure:

{
    "$schema-URL":"http://json-schema.org/custom-schema.json",
    "no": 1,
    "name": "Lampshade",
    "price": 0
}

Schema:

{
  "$ref": "URL/ref took from JSON file"
}

is this possible to validate dynamically or any other way?. I'm new to JSON validation thing. Please suggest some solution.

Thanks...

Upvotes: 0

Views: 33

Answers (1)

Jason Desrosiers
Jason Desrosiers

Reputation: 24409

You could use if/then to select which schema to apply depending on the value of $schema-URL.

{
  "allOf": [
    {
      "if": {
        "properties": {
          "$schema-URL": { "const": "https://yourdomain.com/custom-schema.json" }
        },
        "required": ["$schema-URL"]
      },
      "then": { "$ref": "https://yourdomain.com/custom-schema.json" }
    }
    {
      "if": {
        "properties": {
          "$schema-URL": { "const": "https://yourdomain.com/another-custom-schema.json" }
        },
        "required": ["$schema-URL"]
      },
      "then": { "$ref": "https://yourdomain.com/another-custom-schema.json" }
    }
  ]
}

Unfortunately, there isn't a way to use $ref with a value from the data, so you end up with some duplication and a lot of verbosity. It says, if "$schema-URL" is https://yourdomain.com/custom-schema.json, then validate against https://yourdomain.com/custom-schema.json.

Upvotes: 1

Related Questions