2017-08-29 59 views
1

我需要驗證以下數組項。如何使用JSON模式中的任何定義驗證陣列中的每個實例

{ 
    contents: [{ 
     type: "text", 
     content: "This is text context" 
    }, { 
     type: "image", 
     content: "http://image.url" 
    }] 
} 

我需要驗證內容數組中的每一項。

內容對象應該各自具有typecontent屬性。 type可以是「文字」,「圖像」或「視頻」。 對於圖像或視頻,content應該是有效的網址。

爲此我寫了下面的模式。

{ 
    "id": "post", 
    "description": "generell schema for a post", 
    "definitions": { 
     "contents": { 
      "type": "array", 
      "minItems": 1, 
      "items": { 
       "allOf": [ 
        { "$ref": "#/definitions/text" }, 
        { "$ref": "#/definitions/image" }, 
        { "$ref": "#/definitions/video" }, 
        { "$ref": "#/definitions/mention" } 
       ] 
      } 
     }, 
     "text": { 
      "properties": { 
       "type": {"enum": ["text"]}, 
       "content": {"type": "string"} 
      }, 
      "required": [ 
       "content", 
       "type" 
      ] 
     }, 
     "image": { 
      "properties": { 
       "type": {"enum": ["image"]}, 
       "content": { 
        "type": "string", 
        "format": "url" 
       } 
      }, 
      "required": [ 
       "content", 
       "type" 
      ] 
     }, 
     "video": { 
      "properties": { 
       "type": {"enum": ["video"]}, 
       "content": { 
        "type": "string", 
        "format": "url" 
       } 
      }, 
      "required": [ 
       "content", 
       "type" 
      ] 
     } 
    } 

} 

但是,上面的JSON與我的模式無效。它說data.contents[0].type should be equal to one of the allowed values

如果我使用oneOf而不是allOf它是有效的。但圖片內容可以是沒有有效網址的字符串。

什麼是正確的模式?

+0

問題是....? – Pedro

回答

0

對於初學者,當您應該使用oneOf時,您正在使用allOf

根項目還需要一個屬性定義。希望以下更改可幫助您獲得所需的解決方案或指引您朝着正確的方向發展。

{ 
    "id": "post", 
    "description": "generell schema for a post", 
    "properties": { 
     "contents": { 
      "type": "array", 
      "minItems": 1, 
      "items": { 
       "oneOf": [ 
        { "$ref": "#/definitions/text" }, 
        { "$ref": "#/definitions/image" }, 
        { "$ref": "#/definitions/video" }, 
        { "$ref": "#/definitions/mention" } 
       ] 
      } 
     } 
    } 
    "definitions": { 
     "text": { 
      "properties": { 
       "type": {"enum": ["text"]}, 
       "content": {"type": "string"} 
      }, 
      "required": [ 
       "content", 
       "type" 
      ] 
     }, 
     "image": { 
      "properties": { 
       "type": {"enum": ["image"]}, 
       "content": { 
        "type": "string", 
        "format": "url" 
       } 
      }, 
      "required": [ 
       "content", 
       "type" 
      ] 
     }, 
     "video": { 
      "properties": { 
       "type": {"enum": ["video"]}, 
       "content": { 
        "type": "string", 
        "format": "url" 
       } 
      }, 
      "required": [ 
       "content", 
       "type" 
      ] 
     } 
    } 

} 
相關問題