2013-11-22 72 views
2

我是JSON和JSON模式驗證的新手。合併兩個Json模式

我有以下架構驗證一個員工對象:

{ 
    "$schema":"http://json-schema.org/draft-03/schema#", 
    "title":"Employee Type Schema", 
    "type":"object", 
    "properties": 
    { 
     "EmployeeID": {"type": "integer","minimum": 101,"maximum": 901,"required":true}, 
     "FirstName": {"type": "string","required":true}, 
     "LastName": {"type": "string","required":true}, 
     "JobTitle": {"type": "string"}, 
     "PhoneNumber": {"type": "string","required":true}, 
     "Email": {"type": "string","required":true}, 
     "Address": 
     { 
      "type": "object", 
      "properties": 
      { 
       "AddressLine": {"type": "string","required":true}, 
       "City": {"type": "string","required":true}, 
       "PostalCode": {"type": "string","required":true}, 
       "StateProvinceName": {"type": "string","required":true} 
      } 
     }, 
     "CountryRegionName": {"type": "string"} 
    } 
} 

,我有以下模式,驗證同樣的員工對象的數組:

{ 
    "$schema": "http://json-schema.org/draft-03/schema#", 
    "title": "Employee set", 
    "type": "array", 
    "items": 
    { 
     "type": "object", 
     "properties": 
     { 
      "EmployeeID": {"type": "integer","minimum": 101,"maximum": 301,"required":true}, 
      "FirstName": {"type": "string","required":true}, 
      "LastName": {"type": "string","required":true}, 
      "JobTitle": {"type": "string"}, 
      "PhoneNumber": {"type": "string","required":true}, 
      "Email": {"type": "string","required":true}, 
      "Address": 
      { 
       "type": "object", 
       "properties": 
       { 
        "AddressLine": {"type": "string","required":true}, 
        "City": {"type": "string","required":true}, 
        "PostalCode": {"type": "string","required":true}, 
        "StateProvinceName": {"type": "string","required":true} 
       } 
      }, 
      "CountryRegionName": {"type": "string"} 
     } 
    } 
} 

能否請你告訴我如何合併它們,這樣我可以使用一個模式來驗證單個員工對象或整個集合。謝謝。

回答

1

(注:這個問題也被要求在JSON Schema Google Group,而這個答案是從那裏調整。)

隨着「$ref」,你可以有這樣的事情對你的數組:

{ 
    "type": "array", 
    "items": {"$ref": "/schemas/path/to/employee"} 
} 

如果你想要的東西是一個數組或一個單一的項目,那麼你可以使用「oneOf」:

{ 
    "oneOf": [ 
     {"$ref": "/schemas/path/to/employee"}, // the root schema, defining the object 
     { 
      "type": "array", // the array schema. 
      "items": {"$ref": "/schemas/path/to/employee"} 
     } 
    ] 
} 

最初的Google網上論壇答案還包含一些關於使用"definitions"來組織模式的建議,以便所有這些變體可以存在於同一個文件中。