javascript - AJV 自定义关键字验证

标签 javascript json validation jsonschema ajv

我正在使用 AJV 库来验证我的 JSON 架构。我希望能够将 Startdate 验证为一个字符串。在不是字符串的情况下,应该转换为N/A。目前,它只能将 undefined 转换为 N/A

但是,在这些情况下它不会按预期工作:

  • null -> "null"
  • 0 --> “0”
  • 正确 --> “正确”

如果我希望将以上所有内容都转换为 N/A 字符串,我的 customKeyword 函数会是什么样子?

JSON 响应:

jsonResponse: {
  "Issue": {
    "StartDate": "December 17, 1995 03:24:00"
  }
}

架构:

var ajv = new Ajv({
    useDefaults: true,
    coerceTypes: 'undefined'
});

const schema = {
    "type": "object",
    "properties": {
        "Issue": {
            "type": "object",
            "properties": {
                "StartDate": {
                    "type": "string"
                    "default": "N/A",
                    "stringTypeChecker"
                }
            }
        }
    }
}

添加关键字函数:

ajv.addKeyword('stringTypeChecker', {
  modifying: true,
  validate: function(){
    let foo = []
    console.log(foo)
  }
});

var valid = ajv.validate(schema, jsonResponse);

最佳答案

您不需要 coerceTypes 选项。

关键字需要是:

ajv.addKeyword('stringTypeChecker', {
  modifying: true,
  schema: false, // keyword value is not used, can be true
  valid: true, // always validates as true
  validate: function(data, dataPath, parentData, parentDataProperty){
    if (typeof data != 'string' && parentData) // or some other condition
      parentData[parentDataProperty] = 'N/A';
  }
});

架构:

{
  "type": "object",
  "properties": {
    "Issue": {
      "type": "object",
      "properties": {
        "StartDate": {
          "type": "string",
          "default": "N/A",    
          "stringTypeChecker": true
        }
      }
    }
  }
}

关于javascript - AJV 自定义关键字验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42819408/

相关文章:

javascript - Grunt 从文件重新加载 JSON 并更新任务选项

java - 有没有一种有效的方法来检查字符串是否代表日期?

javascript - 每个输入的 Angular 表单验证类

javascript - 如何消除此错误(通过选择器查找元素)

javascript - 以不推荐使用的方式模拟键盘按下?

javascript - Highcharts:如何创建年龄组、性别、访问次数的详细饼图?

javascript - 如何以编程方式识别和终止无限循环中的 JavaScript?

javascript - 从数据表创建复杂的 json C#

javascript - 将对象/数组转换为 JSON?

java - Apache Commons UrlValidator