如何使用 json 架构文件测试 json 文件

ann*_*ani 5 javascript json jsonschema

我是 json 的新手。我正在学习 Json 模式中的更多内容,但在针对 json-schema.json 文件测试user.json文件时我无能为力。请注意,我需要使用 javascript 变量进行测试,该变量应返回 true 或 false 以进一步处理。特此粘贴我的文件。

json-schema.json

{
  "description": "Any validation failures are shown in the right-hand Messages pane.",
  "type": "object",
  "properties": {
    "foo": {
      "type": "number"
    },
    "bar": {
      "type": "string",
      "enum": [
        "a",
        "b",
        "c"
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

用户.json

{
 "foo": 12345,
 "bar": "a"
}
Run Code Online (Sandbox Code Playgroud)

当我在http://jsonschemalint.com/#/version/draft-05/markup/json中测试上述代码时 ,它说user.json的格式正确。但我需要在本地测试

提前致谢。

quo*_*Bro 4

您可以使用JSON 模式验证器之一。

使用这些库之一的示例ajv

import Ajv from 'ajv';

import schema from 'schema.json';
import data from 'data.json';

function isValid(schema, data) {
  const ajv = new Ajv();
  const valid = ajv.validate(schema, data);

  if (!valid) {
    console.log(ajv.errors);
    return false;
  }

  return true;
}
Run Code Online (Sandbox Code Playgroud)