json - Json Schema Validation - 引用子模式
问题描述
我正在尝试针对具有以下结构的模式验证 json 数据:
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"$id": "https://foo.bar/my.schema.json",
"$def": {
"parentType": {
"type": "object",
"properties": {
"child": {
"$ref": "#/$def/childType"
}
},
"required": [
"child"
]
},
"childType": {
"type": "object",
"properties": {
"name": {
"type": "string"
}
},
"required": [
"name"
]
}
},
"type": "object",
"properties": {
"parent": {
"$ref": "#/$def/parentType"
}
},
"required": [
"parent"
]
}
以下是json数据:
{
"parent": {
"child": {
"name": "aaa",
}
}
}
如何通过 json 模式验证确保以下字段/parent/child/name的值是aaa或bbb?
我不想对 childType 定义添加限制,因为我想保留 childType“通用”的类型定义,并稍后在$def
块之外添加限制。这样,我可以将相同的 childType 用于不同的场景,其中name
可能不是“aaa”或“bbb”。
谢谢!
解决方案
当您使用 draft2019-09
时,您可以$ref
与其他关键字一起使用。这在早期的草稿中是不允许的,例如draft-07
.
例如,与其拥有...
"properties": {
"parent": {
"$ref": "#/$def/parentType"
}
},
你可以有...
"properties": {
"parent": {
"$ref": "#/$def/parentType",
"enum": ["aaa", "bbb"]
}
}
如果要使用多个引用,则需要将它们作为包装在allOf
.
推荐阅读
- c++ - 如何在后台运行的 c++ 中编写一个 cp 函数(在 linux shell 中)?
- c - 释放 uintptr_t 指向的内存
- python - Google kickstart 2020 round A 错误答案
- android - 如何按小时获取我的应用程序屏幕时间?
- python - 为什么我的函数第二次从 python while 循环中调用时会崩溃?
- python - 如何在 JSON 文件中写入预先存在的嵌套字典?
- java - 在 Maven 中使用日期作为版本的最佳实践
- python - 我在 127.0.0.1:21 收听,但没有显示任何内容。我正在关注 Black Hat Python 一书。我应该发送一些东西以便收听吗?
- python - 使用循环编辑数据框
- javascript - 如何在 Deck.gl 中动态切换多个图层?