【问题标题】:JSON-schema exclude properties (opposite to required properties)JSON 模式排除属性(与必需属性相反)
【发布时间】:2021-12-07 18:51:34
【问题描述】:

在 JSON 模式中,可以要求对象中的某些键,请参阅此示例,取自 json schema docs

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "email": { "type": "string" },
    "address": { "type": "string" },
    "telephone": { "type": "string" }
  },
  "required": ["name", "email"]
}

我需要相反:有没有办法禁止防止某个键在对象中?具体来说,我想防止用户在对象中拥有一个空键:

{
    "": "some string value"
}

【问题讨论】:

    标签: jsonschema


    【解决方案1】:

    您可以按名称排除某些键:

    {
     "not": {
      "anyOf": [
        { "required": [ "property1" ] },
        { "required": [ "property2" ] },
        { "required": [ "property3" ] },
        ...
      ]
    }
    

    https://json-schema.org/understanding-json-schema/reference/combining.html

    【讨论】:

      【解决方案2】:

      除了使用 not 语法排除键(参见 Ether 的回答)之外,还可以使用 property-names 来实现目标。

      在以下示例中,所有键都必须映射到字符串 URI。我们还排除所有非字母数字键(通过pattern),或没有特定长度(通过minLength)。除此之外,我们对键没有任何限制。

      "SomeKeyToBeValidated": {
        "type": "object",
        "properties": { },
        "propertyNames": {
          "type": "string",
          "minLength": 1,
          "pattern": "^[a-zA-Z0-9]*$"
        },
        "additionalProperties": {
          "type": "string",
          "format": "uri"
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-01
        相关资源
        最近更新 更多