我生成了以下 JSON:
{
"someString" : "example",
"obj1" : {
"opt1" : 1,
"opt2" : 1,
"opt3" : "aaa"
},
"obj2" : {
"opt1" : 55,
"opt2" : 55,
"opt3" : "bbb"
}
}
并且将会有更多具有相同数据类型(opt1、opt2、opt3)的对象(obj1、obj2、obj3、obj4、...)
现在我想为此创建架构,但我不知道如何在架构中组合所有这些对象。
编辑:
我创建了架构:
root: {
"type" : "object",
"oneOf" : [
{
"properties" : {
"someString" : { "type" : "string" }
},
"patternProperties" : { "^.*$" : { "$ref" : "./schemas/myPatternProperties.json#" } },
"additionalProperties" : false }
}
]
}
和 myPatternProperties.json 看起来:
{
"type" : "object",
"properties" : {
"opt1" : { "type" : "number" },
"opt2" : { "type" : "number" },
"opt3" : { "type" : "string" },
}
"required" : [ "opt1", "opt2", "opt3" ]
}
有什么问题吗,因为我生成的 JSON 仍未被识别为此架构类型。
最佳答案
据我了解,您的问题是描述具有相同类型和一些命名规则的大量属性的对象
。要解决此问题,您必须指定 patternProperties
部分
{
"patternProperties": {
"^(/[^/]+)+$": { "$ref": "http://some.site.somewhere/entry-schema#" }
}
该构造指定属性的匹配模式
。示例how to use patternProperties欲了解更多信息,请访问 specification
更新
实际上完整的方案一定是这样的
{
"$schema": "http://json-schema.org/draft-06/schema#",
"type": "object",
"properties": {
"someString": {
"type": "string"
}
},
"patternProperties": {
"^obj([0-9]+)$": {
"$ref": "#/definitions/objEntity"
}
},
"additionalProperties": false,
"required": [ "someString" ],
"definitions": {
"objEntity": {
"type": "object",
"properties": {
"opt1": { "type": "number" },
"opt2": { "type": "number" },
"opt3": { "type": "string" }
},
"required": ["opt1", "opt2", "opt3"]
}
}
}
当然,您可以将该方案拆分为多个文件,并更改类型定义的链接。
关于JSON 模式 - 具有相同数据类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47809519/