我想创建一个JSON模式,定义两个实体:region
和country
。
country
的JSON模式如下:
{
"$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",
}
}
}
}
这允许我在一个文件中定义国家,我们称之为countries.json
:
[
{ "code": "GB", "name": "United Kingdom"},
{ "code": "US", "name": "United States of America"}
]
我现在想为region
定义一个模式。下面是一个我认为有效的示例文件:
[
{ "name": "Europe", "countries": [ "GB" ] },
{ "name": "North America", "countries": [ "US" ] }
]
需要根据countries.json
的内容验证countries
属性。如何才能做到这一点?我不想使用enum
类型并在region
模式中重复国家列表
JSON模式只能使用模式中的值进行验证。您不能任意查询一些非模式JSON(如countries.json
)来获取允许的值。我建议做一些事情,比如写一个脚本,从countries.json
生成一个国家代码枚举模式,然后在你的地区模式引用该模式。你会得到这样的结果,
{
"$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" }
}
}