2016-10-28 66 views
2

我有一個模式來驗證JSON。jsonschema - 具有靜態屬性的動態屬性

對於某些屬性,我需要它們具有某些類型的值。

  • 如果 「ATTR」 屬性爲 「a」,然後 「VAL」 屬性應該是 「整數」
  • 如果 「ATTR」 屬性爲 「x」,則 「VAL」 屬性應該是 「布爾」
  • 如果 「ATTR」 屬性爲 「b」,然後 「VAL」 屬性應該是 「字符串」 與 格式的 「IPv4」

等等...

這一點,我可以oneOff定義。對於所有其他的「屬性」屬性,我需要它們具有某種格式,有點像捕獲所有,「val」屬性是「字符串」。

  • 如果「attr」匹配pattern,那麼「val」屬性應該是「string」。

可以這樣做。

這是我現在的模式。

{ 
    "$schema": "http://json-schema.org/draft-04/schema#", 
    "type": "object", 
    "properties": { 
    "name": { 
     "title": "name", 
     "type": "string" 
    }, 
    "attribute": { 
     "title": "attributes", 
     "type": "object", 
     "$ref": "#/definitions/expr", 
    } 
    }, 
    "definitions": { 
    "expr": { 
     "properties": { 
     "attr": { 
      "title": "attribute" 
     }, 
     "val": { 
      "title": "val" 
     } 
     }, 
     "required": ["val", "attr"], 
     "oneOf": [ 
     { 
      "properties": { 
      "attr": {"enum": ["a","b"]}, 
      "val": {"type": "integer"} 
      } 
     }, 
     { 
      "properties": { 
      "attr": {"enum": ["x"]}, 
      "val": {"type": "boolean"} 
      } 
     }, 
     { 
      "properties": { 
      "attr": {"pattern": "^[-A-Za-z0-9_]*$", "maxLength": 255}, 
      "val": {"type": "string"} 
      } 
     } 
     ] 
    } 
    }, 
    "additionalProperties": false, 
    "required": [ 
    "name", 
    "attribute" 
    ] 
} 

問題是我試圖限制值類型的屬性,也匹配catchall格式。所以當我期待一個整數值時,它傳遞的是字符串值。

例如:

下面JSON將通過模式的基礎上,oneOff

{ 
    "name": "shouldpass", 
    "attribute": { 
    "attr": "a", 
    "val": 1 
    } 
} 

下面JSON將通過第一項,基於oneOff的最後一個項目。

{ 
    "name": "shouldpass2", 
    "attribute": { 
    "attr": "h", 
    "val": "asd" 
    } 
} 

以下JSON失敗,基於oneOff的第一個項目,但它也傳遞,因爲它是匹配oneOff的最後一個項目。

{ 
    "name": "shouldfail", 
    "attribute": { 
    "attr": "a", 
    "val": "string" 
    } 
} 

如何實現這個目標?

回答

1
在過去的子模式

您架構ATTR可能是:

{ 
    "pattern": "^[-A-Za-z0-9_]*$", 
    "not": { "enum": ["a", "b", "x"] }, 
    "maxLength": 255 
} 

或者,而不是「oneOf」你可以使用「開關」的關鍵字從下一個JSON-架構版本建議:http://epoberezkin.github.io/ajv/keywords.html#switch-v5-proposal

它在Ajv中實現(我是作者)。