jsonschema - 有一个属性使用 JSON Schema 定义另一个数组属性中的类型吗?
问题描述
鉴于此示例 JSON:
{
"type": "number",
"values": [ 34, 42, 99 ]
}
是否可以定义 JSON Schema 以确保values
数组的内容是另一个属性中指定的类型(在本例中type
)?
上面type
是说数组values
只能包含整数(使用说明符“数字”)。
或指定values
包含字符串:
{
"type": "string",
"values": [ "hello", "world" ]
}
解决方案
是的,但是您必须为if/then
要支持的每种类型编写一个块。
理解 JSON 模式有一个部分if/then/else
:http: //json-schema.org/understanding-json-schema/reference/conditionals.html
这是一个解释如何if/then/else
工作的摘录。
例如,假设您想编写一个模式来处理美国和加拿大的地址。这些国家/地区有不同的邮政编码格式,我们希望根据国家/地区选择要验证的格式。如果地址在美国,则 postal_code 字段是“邮政编码”:五位数字后跟可选的四位数字后缀。如果地址在加拿大,则 postal_code 字段是一个六位字母数字字符串,其中字母和数字交替出现。
{
"type": "object",
"properties": {
"street_address": {
"type": "string"
},
"country": {
"enum": ["United States of America", "Canada"]
}
},
"if": {
"properties": { "country": { "const": "United States of America" } }
},
"then": {
"properties": { "postal_code": { "pattern": "[0-9]{5}(-[0-9]{4})?" } }
},
"else": {
"properties": { "postal_code": { "pattern": "[A-Z][0-9][A-Z] [0-9][A-Z][0-9]" } }
}
}
对于您想要支持的每种类型,您都需要编写if/then
对象,并将它们全部包装在一个allOf
.
推荐阅读
- c - 我正在编写一个程序来执行先到先服务算法,它显示分段错误
- sql - (SQL Server 2017) 我收到错误消息 8152,我不知道为什么
- asp.net-mvc - 如何在 ASP.NET MVC 中的 WebServer 中仅上传修改后的 .cs 文件?
- ios - 在 iOS 13.0 及更高版本中,后台计时器在 30 秒后不工作。有什么解决办法吗?
- python - 如何在 Azure DataBricks 中获取 runID 或 processid?
- java - 我想使用 PHP 开发一个 Android 聊天应用程序。我该怎么做?不使用 Google Firebase 云消息传递和 AWS
- go - 有什么方法可以通过引用传入数组的函数来传递数组?
- c++ - 未定义对“IoTHubClient_LL_UploadToBlob_Destroy”的引用
- kubernetes - Kubernetes 就绪 (http) 探测失败,但没有就绪状态 (http) 工作正常
- php - PHP Word 发回不可读的文件