1

根据规范(http://json-schema.org/schema),模式关键字之间没有互斥。例如,我可以创建以下架构:

{ 
    "properties" : {
        "foo" : {"type" : "string"}
    }
    "items" : [
       {"type" : "integer" },
       {"type" : "number" }
    ]
}

此架构是否会同时针对对象和数组进行验证?如果是这样,则意味着关键字之间存在“或”关系。

但是如果我们考虑以下模式:

{ 
    "anyOf" : [
        { "type" : "string",},
        { "type" : "integer"}
    ]
    "not" : {
       { "type" : "string",
         "maxLength" : 5
       }
    }
}

最实用的解释方法是 anyOf 和 not 关键字之间的“与”关系。

我在 v4 草案中找不到任何关于关键字如何在逻辑上相互作用的指示。谁能指出我可以回答这个问题的文档/标准?

4

2 回答 2

1

关键字始终是“与”关系。数据必须满足模式中的所有关键字。

propertiesanditems关键字不指定对象的类型(您必须为此使用)type。相反,它们只对特定类型有意义,否则会被忽略。所以properties实际上意味着:

如果数据是对象,则适用以下属性定义...

这意味着{"properties":{...}}它将匹配任何字符串,因为properties对于不是对象的值会被忽略。items实际上意味着:

如果数据是数组,则适用以下项定义...

所以 AND 组合看起来像:

(如果数据是对象,则properties适用)AND(如果数据是数组,则items适用)

于 2015-01-08T20:50:59.137 回答
1

As the spec clearly dictates, some keywords are only relevant for one particular type of JSON value, or all of them.

So, for instance, properties only applies if the JSON value you validate is a JSON Object. On any JSON value which is NOT an object, it will not apply (another way to understand it is that if the JSON value to validate is not a JSON Object, validation against this keyword will always succeed).

Similarly, items will only apply if the JSON value is a JSON Array.

Now, some other keywords apply for all types; among these are enum, allOf, anyOf, oneOf, type. In each case, the validation rules are clearly defined in the specification.

In short: you should consider what type of value is expected. The easiest way to force a value to be of a given type in a schema is to use type, as in:

"type": "integer"

BUT this keyword will nevertheless be applied INDEPENDENTLY of all others in the validation process. So, this is a legal schema:

{
    "type": "integer",
    "minItems": 1
}

If an empty JSON Array is passed for validation, it will fail for both keywords:

  • type because the value is not an array;
  • minItems because the value is an array but it has zero elements, which is illegal for this particular keyword since it expects one element in the array at least.

Note that the result of validation is totally independent of the order in which you evaluate keywords. That is a fundamental property of JSON Schema. And it is pretty much a requirement that it be so, since the order of members in a JSON Object is irrelevant ({ "a": 1, "b": 2 } is the same JSON Object as { "b": 2, "a": 1 }).

And of course, if only ONE keyword causes validation to fail, the whole JSON value is invalid against the schema.

于 2015-01-08T21:28:31.737 回答