I would like to create a JSON schema that defines two entities: region
and country
.
The JSON schema for country
is as follows:
{
"$id":"https://example.com/arrays.schema.json",
"$schema":"http://json-schema.org/draft-07/schema#",
"description":"A list of countries",
"type":"array",
"items":{
"type":"object",
"required":[
"code",
"name"
],
"properties":{
"code":{
"type":"string",
"maxLength": 2,
"minLength": 2
},
"name":{
"type":"string",
}
}
}
}
This allows me to define countries in a file, lets call it countries.json
:
[
{ "code": "GB", "name": "United Kingdom"},
{ "code": "US", "name": "United States of America"}
]
I would now like to define a schema for region
. Here is an example file that I would consider valid:
[
{ "name": "Europe", "countries": [ "GB" ] },
{ "name": "North America", "countries": [ "US" ] }
]
The countries
attribute needs to be validated against the contents of countries.json
. How can this be achieved? I do not want to use the enum
type and repeat the list of countries in the region
schema
JSON Schema can only validate using values in a schema. You can't arbitrarily query some non-schema JSON such as countries.json
to get the allowed values. I suggest doing something like writing a script that generates an country code enum schema from countries.json
and then referencing that schema in your regions schema. You'd end up with something like this,
{
"$id":"https://example.com/countries.schema.json",
"$schema":"http://json-schema.org/draft-07/schema#",
... the schema from the question ...
}
{ // generated from countries.json
"$id":"https://example.com/country-codes.schema.json",
"$schema":"http://json-schema.org/draft-07/schema#",
"enum": ["GB", "US", ...]
}
{
"$id":"https://example.com/region.schema.json",
"$schema":"http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": { "type": "string" },
"countries": { "$ref": "country-codes.schema.json" }
}
}