簡體   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