[英]JSON schema definitions or oneOf in array of objects?
I need to express an array of different objects in a schema. 我需要在模式中表达一组不同的对象。 The array, called
contents
, can contain any number of elements, but they must be one of two types of object : One type of object represents a piece of text, the other type of object represents an image. 该数组称为
contents
,可以包含任意数量的元素,但是它们必须是两种类型的对象之一 :一种类型的对象表示一段文本,另一种类型的对象表示图像。
So far, I've not been able to find a way to enforce the validation correctly. 到目前为止,我还没有找到正确执行验证的方法。 It seems (nested)
required
inside a oneOf
doesn't work, so I tried using definitions
but that doesn't seem to fit. 似乎(嵌套)在
oneOf
中required
的oneOf
不起作用,因此我尝试使用definitions
但这似乎不合适。
I've tried a few online validators, but they seem happy for me to add illegal values in item-2
value
object. 我尝试了一些在线验证器,但他们似乎很高兴我在
item-2
value
对象中添加非法值。 Its the value
property that seems to be the biggest problem. 它的
value
属性似乎是最大的问题。 Unfortunately, due to legacy issues, I'm stuck with this being an object in an array. 不幸的是,由于遗留问题,我坚持认为这是数组中的对象。
Is it possible to validate and enforce correct type/requirements for this object? 是否可以验证和强制执行此对象的正确类型/要求?
(this is the data, not a schema. Unfortunately, we also used the keyword type
when we design the original json layout!) (这是数据,而不是模式。不幸的是,在设计原始json布局时,我们还使用了关键字
type
!)
{
"uuid":"780aa509-6b40-4cfe-9620-74a9659bfd59",
"contents":
[
{
"name":"item-1",
"label":"My editable text Label",
"value":"This text is editable",
"type":"text"
},
{
"name":"item-2",
"label":"My editable image label",
"index":0,
"type":"image",
"value":
[
{
"name":"1542293213356.png",
"rect":[0,0,286,286]
}
]
}
],
"version":"2.0"
}
Well, I think this is it, though the online validator doesn't seem 100% reliable. 好吧,我想就是这样,尽管在线验证器似乎并非100%可靠。 Editing the values isn't always invalidating the object.
编辑值并不总是会使对象无效。
{
"$schema": "http://json-schema.org/draft-06/schema#",
"type": "object",
"properties": {
"uuid": { "type": "string" },
"version": { "type": "string" },
"contents": {
"$ref": "#/definitions/contents"
},
},
"required": ["uuid", "version"],
"definitions": {
"image": {
"type": "object",
"properties": {
"name": { "type": "string" },
"label": { "type": "string" },
"type": { "enum": ["image", "text"] },
"value": { "type": "object" }
},
"required": ["name", "label", "type", "value"]
},
"text": {
"type": "object",
"properties": {
"name": { "type": "string" },
"label": { "type": "string" },
"type": { "enum": ["image", "text"] },
"value": { "type": "string" }
},
"required": ["name", "label", "type", "value"]
},
"contents": {
"type": "array",
"contains": {
"oneOf": [
{ "$ref": "#/definitions/image" },
{ "$ref": "#/definitions/text" }
]
},
},
},
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.