json - 如何在 JSON Schema Draft-4 中创建所需的对象键?
问题描述
我正在尝试为以下内容定义 json 架构:
{
"user_id" :{
"default" : ["a","b","c"]
"unknown_key1" : ["xyz","def","ekj"]
"unknown_key2" : []
}
}
“默认”键应始终存在于 user_id 映射中。其余的键是未知的,可以是任何数字。您能帮忙定义一下 JSON 模式吗?
我已经定义了架构:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "$id$",
"description": "-1",
"definitions": {
"user_id": {
"type": "object",
"minProperties": 1,
"patternProperties": {
"^[A-Za-z0-9]+": {
"type": "string",
"pattern": "^[A-Za-z0-9]+$"
}
},
"additionalProperties": false
}
},
"type": "object",
"minProperties": 1,
"additionalProperties": false,
"properties": {
"user_id": {
"$ref": "#/definitions/user_id"
}
},
"anyOf": [
{
"required": [
"v"
]
}
]
}
不确定如何强制包括默认字段。
解决方案
您在子模式required
中使用关键字user_id
。
...
"definitions": {
"user_id": {
"type": "object",
"minProperties": 1,
"required": ["default"],
"patternProperties": {
"^[A-Za-z0-9]+": {
"type": "string",
"pattern": "^[A-Za-z0-9]+$"
}
},
"additionalProperties": false
}
}
...