eag*_*der 4 javascript validation json jsonschema ajv
我正在使用 AJV 库来验证我的 JSON 模式。我希望能够验证Startdate
为字符串。如果它不是字符串,则应将其转换为N/A
. 目前,它仅转换undefined
为N/A
.
但是,在这些情况下,它不会按预期工作:
null
-> "空"如果我想将上述所有内容转换为N/A
字符串,我的 customKeyword 函数会是什么样子?
JSON 响应:
jsonResponse: {
"Issue": {
"StartDate": "December 17, 1995 03:24:00"
}
}
Run Code Online (Sandbox Code Playgroud)
架构:
var ajv = new Ajv({
useDefaults: true,
coerceTypes: 'undefined'
});
const schema = {
"type": "object",
"properties": {
"Issue": {
"type": "object",
"properties": {
"StartDate": {
"type": "string"
"default": "N/A",
"stringTypeChecker"
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
添加关键字函数:
ajv.addKeyword('stringTypeChecker', {
modifying: true,
validate: function(){
let foo = []
console.log(foo)
}
});
var valid = ajv.validate(schema, jsonResponse);
Run Code Online (Sandbox Code Playgroud)
您不需要 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';
}
});
Run Code Online (Sandbox Code Playgroud)
架构:
{
"type": "object",
"properties": {
"Issue": {
"type": "object",
"properties": {
"StartDate": {
"type": "string",
"default": "N/A",
"stringTypeChecker": true
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5851 次 |
最近记录: |