Onu*_*rım 3 dependencies json jsonschema
这是简化的 JSON-Schema:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "user",
"type": "object",
"properties": {
"account": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["COMPANY", "PERSON"]
}
},
"required": ["type"]
},
"person": {
"type": "object",
"properties": {
"firstName": { "type": "string" },
"lastName": { "type": "string" }
},
"required": ["firstName", "lastName"]
},
"company": {
"type": "object",
"properties": {
"name": { "type": "string" },
"taxNumber": { "type": "string" }
}
}
},
"required": ["account", "person"]
}
Run Code Online (Sandbox Code Playgroud)
我想要实现的是:
account.type设置为"COMPANY":
company对象及其属性应该是必需的。account.type为"PERSON":
company 对象应该是可选的。company对象存在,company.name并且company.taxNumber应该是必需的。这可以通过在 a 下定义两个长子模式来实现,oneOf但这意味着太多的重复和复杂的模式,因为accountandcompany比这个简化版本有更多的属性。
AFAIK,在模式中定义特定值的唯一方法是将enum关键字与单个项目一起使用。我用dependencies关键字试过这个,但没有帮助。
你能想出一种不改变数据对象结构的方法吗?
小智 5
在Draft-07下,您可以通过有条件地应用架构要求来实现:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"id": "user",
"type": "object",
"properties": {
"account": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["COMPANY", "PERSON"]
}
},
"required": ["type"]
},
"person": {
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
}
},
"required": ["firstName", "lastName"]
},
"company": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"taxNumber": {
"type": "string"
}
}
}
},
"if": {
"properties": {
"account": {
"const": {
"type": "COMPANY"
}
}
}
},
"then": {
"required": ["account", "person", "company"]
},
"else": {
"required": ["account", "person"]
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个对其进行验证的工作示例:
{
"account": {
"type": "COMPANY"
},
"person": {
"firstName": "John",
"lastName": "Doe"
},
"company": {
"name": "XYZ Corp"
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8560 次 |
| 最近记录: |