【问题标题】:> Error: schema is invalid: data should be equal to constant in ajv JSON Schema> 错误:架构无效:数据应等于 ajv JSON 架构中的常量
【发布时间】:2020-10-14 14:28:30
【问题描述】:

我正在尝试通过以下代码将 parced JSON 与 JSON 参考进行比较:

    const Ajv = require("ajv");
    const parsedData = JSON.parse(fs.readFileSync(jsonDataPath, 'utf8'));
    const parsedSchema = JSON.parse(fs.readFileSync(jsonSchemaPath, 'utf8'));
    

    const ajvInstance = Ajv({ allErrors: true });
    const valid = ajvInstance.validate(parsedSchema, parsedData);
    if (valid) {
        console.log("User data is valid");
    } else {
        console.log("User data is INVALID!");
        console.log(ajv.errors);
    }

并得到以下错误:

错误:架构无效:数据应等于常量

如您所见,我尝试将变量转换为 const,但没有任何帮助。

【问题讨论】:

  • 该消息并不意味着您需要将声明从 var 更改为 const

标签: javascript node.js ajv


【解决方案1】:

您收到此错误是因为在您的 JSON 架构中的某处您有一个字段为“const”的定义。此错误与您的 JavaScript 代码无关。

const 关键字用于将一个值限制为单个值。

阅读文档以获取示例和更多信息const

【讨论】:

  • 可能是这样。我检查了我的 parsedSchema 数据,发现可疑行:``` "config": "Common" , "const": "First" , ``` 并将它们替换为 ``` "config": { "const" : "Common" }, "const": { "const": "First" }, ``` 又抛出了错误。我猜这是因为“const”键。
  • 另外,我不得不提到 ajv 不起作用。它断言“0”并且是真的,并说没关系,数据是有效的。似乎无法执行简单的任务((
  • 匹配你的解析数据不利于你的架构定义
  • { "$id": "http://json-schema.org/draft-04/schema#", "$schema": "http://json-schema.org/draft-04/schema#", "flag": true, "myPromises": { "type": "string" }, "element": { "type": "object" }, "screenshot": null, "elementText": { "type": "string" }, "allElementsText": { "type": "string", "pattern": "\\w+const|const+\\w" }, "counter": {"type" : "integer", "minimum" : 10}, "config": { "const": "Common" }, "consst": { "const": "First" }, "parameters": {"type" : "array", "minItems": 8}, "description": {"type" : "string", "minLength" : 6, "maxLength" : 14} }
  • { "flag": "0", "myPromises": [ 1, 2, 3 ], "element": "title", "css": ".dd-ui", "screenshot": null, "elementText": "browser", "allElementsText": "contain the cost", "counter": 113, "config": "not a Common", "const": "the first const", "parameters": [ 3, "", "add", "delete", "update", "", 1, false ], "description": "my first project on js" }
猜你喜欢
  • 2018-09-13
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-31
  • 2016-12-28
相关资源
最近更新 更多