简体   繁体   English

使用AJV定制无效对象的架构解析

[英]Customized schema resolving for invalid objects with AJV

I'm trying to find a way to alter schema validation to find most appropriate schema for a given object. 我正在尝试找到一种更改方案验证的方法,以为给定对象找到最合适的方案。 Let's say we have a schema: 假设我们有一个模式:

{
  "oneOf": [
    {
      "$ref": "#/definitions/a"
    },
    {
      "$ref": "#/definitions/b"
    }
  ],
  "definitions": {
    "a": {
      "type": "object",
      "properties": {
        "prop1": {
          "enum": ["x"]
        }
      },
      "required": ["prop1"]
    },
    "b": {
      "type": "object",
      "properties": {
        "prop1": {
          "enum": ["y"]
        },
        "prop2": {
          "type": "string"
        }
      },
      "required": ["prop1", "prop2"]
    }
  }
}

Now, if I have an object { "prop1": "y" } , I want it to be resolved as of #/definitions/b type, even if it's not really valid for this scheme. 现在,如果我有一个对象{ "prop1": "y" } ,那么我希望它从#/definitions/b类型开始解析,即使它对于该方案不是真的有效。 That is, I want to use just prop1 property for resolving. 也就是说,我只想使用prop1属性进行解析。

I wonder if there is a way to do it using AJV custom keywords, without rebuilding the schema itself? 我想知道是否有一种方法可以使用AJV自定义关键字而不重建架构本身? In particular, if schema is not valid for an object, is it possible to use custom keywords to override it and make it valid? 特别是,如果架构对于对象无效,是否可以使用自定义关键字覆盖它并使之有效?

If the objective is to only report errors from the correct schema you can use either "switch" (with v5 option, it is moved to ajv-keywords from version 5.0.0) or "if/then/else" (it is recommended as it is likely to be added in JSON Schema draft 7): 如果目标是仅报告来自正确模式的错误,则可以使用“开关” (带有v5选项,将其从版本5.0.0移至ajv关键字 )或“如果/然后/否则” (建议使用它可能会添加到JSON模式草案7中):

{
  "id": "schema",
  "if": { "properties": { "prop1": { "const": "x" } } },
  "then": { "$ref": "#/definitions/a" },
  "else": { "$ref": "#/definitions/b" }
}

If you need to know which schema was used for validation you can use a custom keyword to make a note of it: 如果您需要知道用于验证的架构,可以使用自定义关键字对其进行注释:

{
  "id": "schema",
  "if": { "properties": { "prop1": { "const": "x" } } },
  "then": {
    "allOf": [
     { "schemaUsed": "schema#/definitions/a" },
     { "$ref": "#/definitions/a" }
    ]
  },
  "else": {
    "allOf": [
     { "schemaUsed": "schema#/definitions/b" },
     { "$ref": "#/definitions/b" }
    ]
  }
}

The keyword should be defined to store schema ID during validation in some variable so that after validation you could see which one was used. 应该定义关键字以在验证期间将模式ID存储在某个变量中,以便在验证之后可以看到使用了哪个ID。

If you need to get actual schema you can do: 如果您需要获取实际的架构,则可以执行以下操作:

var validate = ajv.getSchema('schema#/definitions/a'); // validating function
var schema = validate.schema; // schema as JSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM