4

我有一个字段状态

如果用户将作业设置为草稿状态,我不想要求描述字段 - 但我希望有一个默认的空字符串。

如果用户发布的工作比我想要的描述是必需的。

我无法弄清楚的是如何在“oneOf - 草稿”数组中设置描述的默认值。

这是我的架构

{
  "schema": "http://json-schema.org/draft-04/schema#",
  "$id": "http://company.com/schemas/job-update.json#",
  "title": "Job",
  "description": "Update job",
  "type": "object",
  "properties": {
    "title": { 
      "type": "string",
      "minLength": 2
    },
    "description": { 
      "type": "string"
     // Can't set default here - as it will apply for the publish status.
    },    
    "status": { 
      "enum": ["draft", "published", "onhold"],
      "default": "draft"
    }
  },
  "oneOf": [
        {
          "description": "Draft jobs do not require any validation",
          "properties": {
            "status": { "enum": ["draft"]}
          },
          "required": [] 
          // SOME WHERE HERE SET DESCRIPTION.default: ""         
        },
        {
          "description": "Published jobs require validation on required fields",
          "properties": {
            "status": { "enum": ["published"]}
          },
          "required": [
            "description"
          ], 
        }        
  ],
  "additionalProperties": false
}
4

1 回答 1

4

不幸的是,使用纯 JSON Schema 是不可能的。

JSON Schema 验证不会修改实例数据。

JSON Schema 中的default关键字是注解关键字。注释关键字用于表示信息,但它们没有验证要求。

Draft-7(当前的)这样说:

此关键字的值没有任何限制。当此关键字的多次出现适用于单个子实例时,实现应该删除重复项。

此关键字可用于提供与特定模式关联的默认 JSON 值。建议默认值对关联的模式有效。

https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-10.2

没有与注释关键词相关的定义行为。

请记住,JSON Schema 的主要用例是定义、验证和注释。

然而...

如果您不关心模式的可移植性,那么ajv实现允许您default在验证期间使用该值来设置键,但这种行为不是由 JSON 模式定义的。

于 2018-10-26T08:20:51.753 回答