我想阻止 json 文件允许 null 作为其有效值。 尝试使用关键字not,但没有成功。
希望以下 json 被验证为 false,因为字段 stats 的值为 null。
{
"stats": "null"
}
请在下面找到我的架构:-
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "http://jsonschema.net#",
"type": "object",
"additionalProperties": false,
"maxProperties": 1,
"properties": {
"stats": {
"id": "http://jsonschema.net/stats#",
"type": "string",
"maxLength": 5,
"minLength": 2,
"additionalProperties": false,
"maxProperties": 1,
"not": {"type": "null"}
}
},
"required": [
"stats"
]
}
虽然我给出了"not": {"type": "null"},但它仍然验证成功。
最佳答案
哇。这里有很多困惑。
问题很简单:
{
"stats": "null"
}
"null"
是一个字符串,因此它是有效的(因为您允许使用字符串)。您的模式不允许这样做,它按您的预期工作:
{
stats: null
}
Ashish Patil 的答案是错误的:在您的架构(而不是您的数据)中,当您指定类型时,类型名称是一个字符串。指定 "not": {"type": null}
无效。您可以指定"not": {"type": "null"}
,但这将是多余的,因为之前的"type": "string"
已经暗示了这一点。
jruizaranguren 接受的答案有效,因为它不允许字符串 “null”
。它没有解决 null
与 "null"
不同的核心混淆。
关于 "type"="string"时的 JSON 模式验证为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31041659/