"type"="string"时的 JSON 模式验证为 null

标签 json validation jsonschema

我想阻止 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/

相关文章:

json - 通过json发送expressjs cookie

php - 我的代码有什么问题?检查每个括号和分号后继续获取 "unexpected end of file"

python - 如何从架构中的 json 文件中获取缺失的字段,反之亦然

javascript - Angular 表单验证 - 将毫秒转换为有效日期对象

python - 重写修饰的子类方法

java - 不会生成数组 List<ComplexType> 而是 List<Object>

javascript - json 模式 : how to transform from one json-schema to another

jquery - 使用 jQuery 和 JSON 填充表单?

python - 解析非标准分号分隔 "JSON"

flash - 将 JSON 转换为自定义 ActionScript 对象?