【发布时间】:2021-07-23 08:07:09
【问题描述】:
我想编写一个包含多个子模式的单个文件 JSON 模式定义,我可以根据负载组合这些子模式。
以下架构验证我的架构正在处理我的示例 JSON 响应。 (响应对象的 payload.role 类型错误,以确保架构捕获此错误!)
为了清楚起见,我在最重要的部分减少了它。可以在此处找到完整的工作示例:https://www.jsonschemavalidator.net/s/3KAaXjtg
架构
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "http://example.com/baseSchema.json",
"type": "object",
"required": [
"payload"
],
"properties": {
"payload": {
"$id": "#/properties/payload",
"type": "object",
// reference the right schema depending on the payload child key
// if `payload.user` reference `userSchema.json`
// if `payload.users` reference `usersSchema.json`
// if `payload.*` reference `*Schema.json`
"$ref": "userSchema.json"
}
},
"definitions": {
"user": {
"$id": "http://example.com/userSchema.json",
"type": "object",
"required": [
"user"
],
"properties": {
"user": {
"type": "object",
"$ref": "userProperties.json"
}
}
},
"users": {
"$id": "http://example.com/usersSchema.json",
"type": "object",
"required": [
"users"
],
"properties": {
"users": {
"type": "array",
"items": {
"$ref": "userProperties.json"
}
}
}
},
"userProperties": {
"$id": "http://example.com/userProperties.json",
"type": "object",
"properties": {
"firstName": {
"$id": "#/properties/payload/properties/user/properties/firstName",
"type": "string"
}
}
}
}
}
回应
{
"status": {
"code": 200,
"description": "User retrieved successfully."
},
"payload": {
"user": {
"firstName": "Joe",
"lastName": "Doe",
"role": "3", // for testing reasons, this is the wrong type!
"email": "doe@example.com",
"customerID": "",
"projects": [
"AIXG5mEg6QLl9rhVSE6m",
"Bs1bHiOIqKclwwis3CNf",
"NC2OUGVZXU35FA7iwRn4"
],
"status": "Status",
"id": "c555BSZnKLdHSRYqrU5hqiQo733j13"
}
}
}
所以我有一个与此响应匹配的baseSchema.json:
{
"status": {},
"payload": {}
}
payload 被某个键(如 payload.user = {} 或 payload.foo = {})扩展,并且根据该键,我想用我的定义之一扩展架构。
以下部分仅适用于密钥user:
"properties": {
"payload": {
"$id": "#/properties/payload",
"type": "object",
// reference the right schema depending on the payload child key
// if `payload.user` reference `userSchema.json`
// if `payload.users` reference `usersSchema.json`
// if `payload.*` reference `*Schema.json`
"$ref": "userSchema.json"
}
},
我未能设置任何conditions(带有allOf、if、else),这将基于payload 键引用正确的子架构。
感谢任何提示和帮助解决这个问题。
【问题讨论】:
-
条件是否互斥?无论哪种方式,解决方案都是相似的,但是如果不磕头,解决方案可能对您不起作用
-
@Relequestual 他们是独家的。只能引用一个 *Schema.json。解决方法类似于什么?
-
不管你的回答如何,解决方案(我会提供)都是相似的
-
啊...跟进问题,您是否提前知道所有可能的密钥?这不能动态完成。
-
是的,可能的键是已知的。我希望有一个动态的解决方案,但我可以看到这在静态文档的上下文中没有意义。
标签: json jsonschema