3

我需要通过以下方式验证 JSON 文件:

const setupSchema = fs.readFileSync(schemaDir +'/setup.json');

并编译:

const setupValidator = ajv.compile(setupSchema);

我的问题是那一行:

console.log( setupValidator('') );

true即使验证器的参数是上面的空字符串,也总是返回。我想加载方式很糟糕,但是......需要问比我更聪明的人。

4

2 回答 2

3

从快速入门指南:(http://json-schema.org/

正在验证或描述的 JSON 文档称为实例,包含描述的文档称为模式。

最基本的模式是一个空白的 JSON 对象,它什么都不约束,什么都允许,什么也不描述:

{}

您可以通过向架构添加验证关键字来对实例应用约束。例如,“type”关键字可用于将实例限制为对象、数组、字符串、数字、布尔值或 null:

{ "type": "string" }

这意味着,如果您的模式是空对象或不使用 JSON 模式词汇表,Ajv 的compile函数将始终生成一个始终通过的验证函数:

var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true});

var schema = {
    foo: 'bar',
    bar: 'baz',
    baz: 'baz'
};

var validate = ajv.compile(schema);

validate({answer: 42}); //=> true
validate('42'); //=> true
validate(42); //=> true

根据 JSON Schema 规范,您setup.json的加载可能不正确或者不是模式。

于 2019-01-03T20:20:15.633 回答
1
// You should specify encoding while reading the file otherwise it will return raw buffer
const setupSchema = fs.readFileSync(schemaDir +'/setup.json', "utf-8");
// setupSchema is a JSON string, so you need to parse it before passing it to compile as compile function accepts an object
const setupValidator = ajv.compile(JSON.parse(setupSchema));
console.log( setupValidator('') ) // Now, this will return false;

而不是上面做的,你可以简单地使用 .json 文件来要求 json 文件require

const setupSchema = require(schemaDir +'/setup.json');
const setupValidator = ajv.compile(setupSchema);
console.log( setupValidator('') );
于 2019-01-03T17:54:26.083 回答