JSON Schema 是否支持深度对象验证?

Dim*_*sky 6 json jsonschema

我正在查看文档,但找不到任何直接或间接的解决方案。

有没有办法在不知道特定对象的确切位置的情况下对 JSON 对象进行验证?

例如,我想验证以下子对象:

{
  "grandParent": {
    "parent": {
      "child": {
        "name": "John"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

该对象可以是更大的 JSON 文件的一部分,其结构如下:

{
  "root": {
    "someKey": {
      "grandParent": ...
    },
    "grandParent": ...,
    ...<go in even deeper>: {
      "grandParent": ...
    }
  }
} 
Run Code Online (Sandbox Code Playgroud)

我可以创建一个 json 模式来验证对象,无论它在哪里吗?

glob 中的类似示例是: root.**.grandParent.parent.child

Rel*_*ual 1

您需要使用additionalProperties、items和 递归引用的组合。

首先,我们定义您要验证的结构。您必须properties为对象的每一层进行定义。

接下来,您希望根级别引用该定义。因为您使用的是 pre Draft 2019-09,所以您需要将该引用包装在allOf.

然后,您需要确保对于对象,值应用了根架构,对于数组,每个项目都应用了根架构。

使用"$ref": "#"解析为模式的根,从而创建循环引用。

有些实现可能不喜欢这样,但大多数应该能够处理它。

这是以下架构的现场演示:https://jsonschema.dev/s/lBrZk

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "definitions": {
    "grandParentToChild": {
        "properties": {
          "grandParent": {
            "properties": {
              "parent": {
                "properties": {
                  "child": {
                    "properties": {
                      "name": {
                        "type": "string"
                      }
                    }
                  }
                }
              }
            }
          }
        }
    }
  },
  "allOf": [
    {
      "$ref": "#/definitions/grandParentToChild"
    }
  ],
  "additionalProperties": {
    "$ref": "#"
  },
  "items": {
    "$ref": "#"
  }
}
Run Code Online (Sandbox Code Playgroud)