【问题标题】:Validate Json Schema验证 Json 架构
【发布时间】:2012-07-19 10:02:23
【问题描述】:

使用json-schema-validator API v4 时出现错误。 我尝试做:

final JsonValidator validator = new JsonValidator(JsonLoader.fromPath("schema.json"));
ValidationReport report = validator.validate(data);

但每次我得到一个错误:# [schema]: unknown keyword contacts

schema.json :
{
    "contacts": {
        "description": "The list of contacts",
        "type": "array",
        "optional": true,
        "items": {
            "description": "A contact",
            "type": "object",
            "properties": {
                "givenName": {
                    "description": "Person's first name",
                    "type": "string",
                    "maxLength": 64,
                    "optional": true
                },
                "familyName": {
                    "description": "A person's last name",
                    "type": "string",
                    "maxLength": 64,
                    "optional": true
                }
            }
        }
    }
}

问候

【问题讨论】:

    标签: json validation jsonschema


    【解决方案1】:

    据我所知,您的数据看起来像这样-> json_data={"contacts":array}。如果这是真的,基本上你最外面的东西是一个对象(基本上是完整的 json 对象本身),你“可能”需要从 json 的“顶级根”开始定义架构 as-> schema.json:

    {
    "description": "the outer json",
            "type": "object",
            "properties": {
                "contacts": {
                              "description": "The list of contacts",
                              "type": "array",
                              "optional": true,
                              "items": {
                                         "description": "A contact",
                                         "type": "object",
                                         "properties": {
                                         "givenName": {
    
    etc.....
    

    请原谅我粗略的压痕。另外,我还没有测试过,请看看它是否有效,如果无效,我建议您提供您的 json_data (至少是示例)和 API 的示例,以便您可以尝试找出问题所在。

    【讨论】:

      【解决方案2】:

      使用 AVJ。无需将数据验证和清理逻辑编写为冗长的代码,您可以使用简洁、易于阅读和跨平台的 JSON Schema 或 JSON 类型定义规范声明对数据的要求,并在数据到达您的应用。

      // validationSchema.js
      
      import Ajv from "ajv";
      import addFormats from "ajv-formats";
      import ajvErrors from "ajv-errors";
      
      const schemas = {
        newUser: {
          {
            type: "object",
            properties: {
              lastName: {
                type: "string",
                minLength: 1,
                maxLength: 255
              },
              firstName: {
                type: "string",
                minLength: 1,
                maxLength: 255
              },
              description: {
                type: "string"
              },
              birthday: {
                type: "string",
                format: "date-time"
              },
              status: {
                type: "string",
                enum: ["ACTIVE", "DELETED"]
              },
            },
            required: ["name"]
          }
        }
      };
      
      const ajv = new Ajv({ allErrors: true });
      
      addFormats(ajv);
      ajvErrors(ajv /*, {singleError: true} */);
      
      const mapErrors = (errorsEntry = []) => {
        const errors = errorsEntry.reduce(
          (
            acc,
            { instancePath = "", message = "", params: { missingProperty = "" } = {} }
          ) => {
            const key = (instancePath || missingProperty).replace("/", "");
      
            if (!acc[key]) {
              acc[key] = [];
            }
      
            acc[key].push(`${key} ${message}`);
      
            return acc;
          },
          []
        );
      
        return errors;
      };
      
      const validate = (schemaName, data) => {
        const v = ajv.compile(schemas[schemaName]);
        let valid = false,
          errors = [];
      
        valid = v(data);
        if (!valid) {
          errors = mapErrors(v.errors);
        }
      
        return { valid, errors };
      };
      
      export default { validate };

      你可以这样验证它:

      import validationSchema from "your_path/validationSchema.js"
      
      const user = {
        firstName: "",
        lastName: "",
        ....
      };
      
      const { valid, errors = [] } = validationSchema.validate("newUser", user);
      
      if(valid){
        console.log("Data is valid!");
      } else {
        console.log("Data is not valid!");
        console.log(errors);
      }

      【讨论】:

        猜你喜欢
        • 2015-10-23
        • 1970-01-01
        • 2017-10-18
        • 1970-01-01
        • 2021-08-03
        • 2015-09-11
        • 2018-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多