繁体   English   中英

JSON模式定义或对象数组中的oneOf?

[英]JSON schema definitions or oneOf in array of objects?

我需要在模式中表达一组不同的对象。 该数组称为contents ,可以包含任意数量的元素,但是它们必须是两种类型的对象之一 :一种类型的对象表示一段文本,另一种类型的对象表示图像。

到目前为止,我还没有找到正确执行验证的方法。 似乎(嵌套)在oneOfrequiredoneOf不起作用,因此我尝试使用definitions但这似乎不合适。

我尝试了一些在线验证器,但他们似乎很高兴我在item-2 value对象中添加非法值。 它的value属性似乎是最大的问题。 不幸的是,由于遗留问题,我坚持认为这是数组中的对象。

是否可以验证和强制执行此对象的正确类型/要求?

(这是数据,而不是模式。不幸的是,在设计原始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"
}

好吧,我想就是这样,尽管在线验证器似乎并非100%可靠。 编辑值并不总是会使对象无效。

{
    "$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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM