Json 可能有两种形式的对象的模式验证

Json schema validation for object which may have two forms

我正在尝试弄清楚如何验证可能有 2 种形式的 JSON 对象。

举例 当没有可用数据时,JSON 可能是

{
  "student": {}
}

当有可用数据时,JSON 可能是

{
  "student":{
  "id":"someid",
  "name":"some name",
  "age":15
 }
}

我用这种方式编写了 JSON 架构,但它似乎不起作用

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "$id": "http://json-schema.org/draft-07/schema#",
    "title": "JSON schema validation",
    "properties": {
        "student": {
            "type": "object",
            "oneOf": [
                {
                    "required": [],
                    "properties": {}
                },
                {
                    "required": [
                        "id",
                        "name",
                        "age"
                    ],
                    "properties": {
                        "id": {
                            "$id": "#/properties/student/id",
                            "type": [
                                "string",
                                "null"
                            ]
                        },
                        "name": {
                            "$id": "#/properties/student/name",
                            "type": [
                                "string",
                                "null"
                            ]
                        },
                        "age": {
                            "$id": "#/properties/student/age",
                            "type": [
                                "number"
                            ]
                        }
                    }
                }
            ]
        }
    }
}

我想知道有没有办法验证它。谢谢!

一个空 properties 对象和一个空 required 对象,什么都不做。

JSON 架构是基于约束的,因为如果您没有明确限制允许的内容,那么默认情况下是允许的。

你很接近,但不完全是。 const 关键字可以取任何值,并且是您想要在 allOf 的第一项中使用的值。 您可以在此处测试以下架构:https://jsonschema.dev/s/Kz1C0

{
  "$schema": "http://json-schema.org/draft-07/schema",
  "$id": "https://example.com/myawesomeschema",
  "title": "JSON schema validation",
  "properties": {
    "student": {
      "type": "object",
      "oneOf": [
        {
          "const": {}
        },
        {
          "required": [
            "id",
            "name",
            "age"
          ],
          "properties": {
            "id": {
              "type": [
                "string",
                "null"
              ]
            },
            "name": {
              "type": [
                "string",
                "null"
              ]
            },
            "age": {
              "type": [
                "number"
              ]
            }
          }
        }
      ]
    }
  }
}