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

时间:2020-09-08 19:25:55

标签: json schema jsonschema

我正在尝试弄清楚如何验证可能具有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"
                            ]
                        }
                    }
                }
            ]
        }
    }
}

我想知道是否有一种方法可以验证它。谢谢!

1 个答案:

答案 0 :(得分:1)

一个空的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"
              ]
            }
          }
        }
      ]
    }
  }
}
相关问题