【问题标题】:JSON schema validation for null when "type"="string"当“type”=“string”时,JSON 模式验证 null
【发布时间】:2015-06-25 05:09:44
【问题描述】:

我想防止 json 文件允许 null 作为它的有效值。 尝试使用关键字,但没有运气。

希望以下 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" } 进行验证,但失败了。你如何验证你的 JSON?
  • 你确定它是“null”而不是“null”吗?因为这是一个字符串,而不是一个“空”值
  • 我正在使用 java 代码通过 jsonSchema 验证 json。但我正在使用 jsonschemalint.com/draft4/# 检查验证,以便以更简单的方式进行测试。

标签: json validation jsonschema


【解决方案1】:

哇。这里有很多混乱。

问题很简单:

{
  "stats": "null"
}

"null" 是一个字符串,因此它是有效的(因为你允许字符串)。您的架构不允许这样做,它可以按您的预期工作:

{
    stats: null
}

Ashish Patil 的回答是错误的:在您的架构(不是您的数据)中,当您指定类型时,类型名称是一个字符串。指定 "not": {"type": null} 无效。您可以指定"not": {"type": "null"},但这将是多余的,因为之前的"type": "string" 已经暗示了这一点。

jruizaranguren 接受的答案有效,因为它不允许 字符串 "null"。它没有解决null"null" 不同的核心混淆。

【讨论】:

    【解决方案2】:

    首先,null 不是字符串。因此,请尝试在您的架构中使用以下内容--

     "stats": {
      "id": "http://jsonschema.net/stats#",
      "type": "string",
      "maxLength": 5,
      "minLength": 2,
      "additionalProperties": false,
      "maxProperties": 1,
      "not": {"type":  null}
    }
    

    但是,在示例 sn-p 中,您提到了如下内容--

    { "stats": "null" }

    所以,如果您真的希望在您的文件中不允许使用 null,那么您的示例文件应该类似于 { "stats": null } 沿着我提供的架构。

    【讨论】:

      【解决方案3】:

      您可以使用“enum”关键字代替“type”。 “null”不是有效的 json 和 json-schema 类型。

      另外的属性和 maxProperties 在统计描述中是无用的。

      {
          "$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
                  "not" : {
                      "enum" : ["null"]
                  }
      
              }
          }, 
          "required" : [
              "stats"
          ]
      }
      

      【讨论】:

      • 感谢 jruizaranguren。完美运行
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      • 2011-06-08
      • 2019-09-10
      • 2011-11-20
      • 2020-11-06
      相关资源
      最近更新 更多