我是定义JSON模式和根据该模式验证JSON的新手。
下面是一个示例json,我想为它定义一个json模式模板进行验证:
{
"version": "1.0",
"config": {
"globalConfig": {
“ClientNames”: [
“client1”, “client2”, “client3”
]
},
“ClientConfigs”: [
{
“ClientName”: “client1”,
“property1”: “some value”,
“property2”: “some value”
},
{
“ClientName”: “client2”,
“property1”: “some value”,
“property2”: “some value”
},
{
“ClientName”: “client3”,
“property1”: “some value”,
“property2”: “some value”
}
]
}
根据我的理解,"ClientConfigs"将是一个对象数组(比如ClientConfig(,它将包含clientName、property1和property2。以下是我认为模式想要的:
{
"$schema": "http://json-schema.org/draft-01/schema#",
"title": "ClientConfig",
"type": "object",
"description": "Some configuration",
"properties": {
"version": {
"type": "string"
},
"config": {
"$ref": "#/definitions/config"
}
},
"definitions": {
"config": {
"type": "object",
"properties": {
"globalConfig": {
"type": "object",
"description": "Global config for all clients",
"properties": {
"ClientNames": {
"type": "array",
"minItems": 1,
"items": {
"type": "string"
}
}
}
},
"ClientConfigs": {
"type": "array",
"description": "List of configs for different clients",
"minItems": 1,
"items": {
"$ref": "#/definitions/ClientConfig"
}
}
}
},
"ClientConfig": {
"type": "object",
"properties": {
"ClientName": {
"type": "string"
},
"property1": {
"type": "string"
},
"property2": {
"type": "string"
}
}
}
}
}
我想用jsonschema验证两件事:
- ClientConfigs数组的每个元素中的ClientName都是"ClientNames"中的值之一,即"ClientConfigs"数组中的单个ClientConfig应仅包含在属性"ClientName"中定义的客户端名称
- "ClientNames"中存在的每个clientName都应定义为"ClientConfigs"数组中的一个元素。更准确地说,ClientConfig是为"ClientNames"属性中存在的每个clientName定义的
根据我的要求,这里有一个无效的例子:
{
"version": "1.0",
"config": {
"globalConfig": {
“ClientNames”: [
“client1”, “client2”, “client3”
]
},
“ClientConfigs”: [
{
“ClientName”: “client4”,
“property1”: “some value”,
“property2”: “some value”
}
]
}
它无效,因为:
- 它没有为客户端1、客户端2和客户端3定义ClientConfig
- 它为"ClientNames"中不存在的client4定义ClientConfig
是否可以使用json模式模板进行这样的验证?如果是,如何验证?
您不能在JSON架构中引用实例数据。这被认为是业务逻辑,超出了JSON模式的范围。