1

我正在尝试创建一个 JSON 模式,该模式可以支持使用属性值验证 JSON 对象,这些属性值可以是常规 JSON 类型或表示有效 JSONpath 表达式的字符串。

例如,给定这个模式:

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "properties": {
    "age": {
      "type": "number"
    }
  }
}

这些 JSON 对象中的任何一个都可能是有效的:

{
  "age": 30 
}

{
  "age" "$.age"
}

我一直在尝试添加一个自定义关键字,jsonPath如下所示:

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "properties": {
    "age": {
      "type": "number",
      "jsonPath": true
    }
  }
}

ajv.addKeyword('jsonPath', {
  valid: true,
  compile: () => data => {
    return /^\$./.test(data)
  }
})

理想情况下,我希望能够检查给定的属性值是否是有效的 JSONPath 字符串,如果是,则批准它。否则让 ajv 运行它自己的验证。

谢谢你的帮助!

4

1 回答 1

1

I don't know if you can prevent other keywords from running. There are multiple ways to apply checks in JSON Schema to the same location, so this would likely be pretty difficult and probably not something that's supported by ajv.

You could build this into your schema.

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "properties": {
    "age": {
      "anyOf": [
        {
          "type": "number"
        },
        {
          "pattern": "REGEX FOR JSON PATH"
        }
      ]

    }
  }
}

You could de-duplicate the regex by using definitions and referencing it using $ref.

于 2019-07-10T09:08:05.783 回答