jsonschema - 使用 Json Schema 的 AJV 修改数据
问题描述
我在 NodeJs 上使用 AJV(另一个 Json 模式验证器)。
我有以下架构
var schema = {
"$id": "testSchema.json",
"type": "object",
"$schema": "http://json-schema.org/draft-06/schema#",
"additionalProperties": false,
"properties": {
"userId": {
"type": "integer"
},
"userName": {
"type": "string"
},
"uniqueID": {
"type": "integer"
}
}
}
我需要用unqiueID
我可以以某种方式传递给 Json 模式或 AJV 的值覆盖属性。我认为上述可以使用 AJV addKeyword 方法完成,尝试使用它但失败了,因为我不知道如何从 AJV 自定义关键字操作(和返回)数据值。是否可以使用 AJV 修改数据?或者还有其他可能的方法吗?谢谢!
解决方案
您可以使用功能创建自定义关键字,该功能将执行您想要的任何数据。
var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true});
ajv.addKeyword('my_id_rewrite', {
type: 'object',
compile: function (sch, parentSchema) {
return function (data) {
console.log(data)
data['my_id']=parentSchema.my_id_rewrite;
return true;
}
}
});
var schema = { "my_id_rewrite": 2 };
var validate = ajv.compile(schema);
o = {"my_id":1}
console.log(validate(o)); // true
console.log(o); // Object {my_id: 2}
推荐阅读
- wix - 使用 $(env.VCINSTALLDIR) 在带有 CNDL0150 的candle.exe 中失败
- python - 无法执行拖放 python selenium
- jquery - 将我的 div 的动画更改为从右向左滑出,而不是淡入
- python - 通过递归生成元素列表
- react-native - 可触摸的不透明度使我的按钮消失
- c# - 刷新关于 Caliburn Micro WPF 中的属性更改的视图
- azure - 无法刷新收藏列表。请稍后再试
- asp.net-mvc - 如何将带有webclient的文件传递给asp.net mvc中的webservice?
- android - 使用免费语言翻译器的运行时应用程序的 Android 本地化(更改语言)
- python - Opencv 相机崩溃,退出代码为 -1073741819 (0xC0000005)