2016-04-14 116 views
4

我很难弄清楚如何根据其中一个属性的值验证对象数组。那么,我有这样一个JSON对象:JSON模式anyOf基于其中一个属性进行验证

{ 
    "items": [ 
     { 
      "name": "foo", 
      "otherProperty": "bar" 
     }, 
     { 
      "name": "foo2", 
      "otherProperty2": "baz", 
      "otherProperty3": "baz2" 
     }, 
     { 
      "name": "imInvalid" 
     } 
    ] 
} 

我想说的是

  1. 项目可以包含anyOf对象,其中名称可以是“富”或“foo2的”
  2. ,如果它是“ foo”的则唯一有效的其他属性(必需)是 ‘otherProperty’
  3. 如果名字是‘foo2的’,那么唯一有效的其他 性质是‘otherProperty2’和‘otherProperty3’既需要
  4. 对于“名称”,“foo”和“foo2”没有其他值是有效的
  5. 对象本身在项目数组中是可选的,有些可能会重复。

我试过各种东西,但我似乎无法得到失败,当我验证。例如,名称“imInvalid”应该导致验证错误。这是我最近的模式迭代。我错过了什么?

{ 
    "$schema": "http://json-schema.org/draft-04/schema#", 
    "type": "object", 
    "required": ["items"], 
    "properties": { 
     "items": { 
      "type": "array", 
      "minItems": 1, 
      "additionalProperties": false, 
      "properties": { 
       "name": { 
        "anyOf": [ 
         { 
          "type": "object", 
          "required": ["name", "otherProperty"], 
          "additionalProperties": false, 
          "properties": { 
           "otherProperty": { "type": "string" }, 
           "name": { "enum": [ "foo" ] } 
          } 
         },{ 
          "type": "object", 
          "required": ["name", "otherProperty2", "otherProperty3" ], 
          "additionalProperties": false, 
          "properties": { 
           "otherProperty2": { "type": "string" }, 
           "otherProperty3": { "type": "string" }, 
           "name": { "enum": [ "foo2" ] } 
          } 
         } 
        ] 
       } 
      } 
     } 
    } 
} 
+0

我认为你是嵌套名称和其他名称内的财产。 – jmugz3

+0

如果你想写一个答案,显示正确的方式,并验证http://json-schema-validator.herokuapp.com这将是伟大的 - 正如我所说,我已经尝试了很多不同的事情在过去的情侣没有运气的日子。以上只是最近的一次。 –

回答

5

你必须使用枚举分开什么是匹配的基本思想,但有一对夫妇错误的位置:

  • JSON模式阵列不具备的特性,他们的项目。
  • 在该属性中,您将名称定义为一个属性,然后保存其他json模式对象。
  • 在你的第二个分支是架构您定义otherProperty3但你的样品是属性被称为anotherProperty3

试试这个稍微修改版本:

{ 
"$schema": "http://json-schema.org/draft-04/schema#", 
"type": "object", 
"required": ["items"], 
"properties": { 
    "items": { 
     "type": "array", 
     "minItems": 1, 
     "additionalProperties": false, 
     "items": { 
      "anyOf": [ 
       { 
        "type": "object", 
        "required": ["name", "otherProperty"], 
        "additionalProperties": false, 
        "properties": { 
         "otherProperty": { "type": "string" }, 
         "name": { "enum": [ "foo" ] } 
        } 
       },{ 
        "type": "object", 
        "required": ["name", "otherProperty2", "anotherProperty3" ], 
        "additionalProperties": false, 
        "properties": { 
         "otherProperty2": { "type": "string" }, 
         "anotherProperty3": { "type": "string" }, 
         "name": { "enum": [ "foo2" ] } 
        } 
       } 
      ] 
     } 
    } 
} 
} 
+0

哦,不!我很亲密。谢谢! –