【问题标题】:how to test a json file with json schema file如何使用 json 模式文件测试 json 文件
【发布时间】:2017-04-08 16:26:40
【问题描述】:

我是 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"
      ]
    }
  }
}

user.json

{
 "foo": 12345,
 "bar": "a"
}

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

提前致谢。

【问题讨论】:

标签: javascript json jsonschema


【解决方案1】:

您可以使用JSON schema validators 之一。

使用这些库之一的示例,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;
}

【讨论】:

    猜你喜欢
    • 2018-06-15
    • 2019-05-06
    • 2017-12-09
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 2018-03-22
    相关资源
    最近更新 更多