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"
}
}
如何實現這個目標?