一个对象的Json Schema示例

Sta*_*ovv 36 schema json jsonschema

我试图通过构建验证两种不同对象类型的模式来弄清楚oneOf是如何工作的.例如一个人(名字,姓氏,运动)和车辆(类型,成本).

以下是一些示例对象:

{"firstName":"John", "lastName":"Doe", "sport": "football"}

{"vehicle":"car", "price":20000}
Run Code Online (Sandbox Code Playgroud)

问题是我做错了什么,我该如何解决它.这是架构:

{
    "description": "schema validating people and vehicles", 
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "required": [ "oneOf" ],
    "properties": { "oneOf": [
        {
            "firstName": {"type": "string"}, 
            "lastName": {"type": "string"}, 
            "sport": {"type": "string"}
        }, 
        {
            "vehicle": {"type": "string"}, 
            "price":{"type": "integer"} 
        }
     ]
   }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试在此解析器中验证它时:

https://json-schema-validator.herokuapp.com/
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

   [ {
  "level" : "fatal",
  "message" : "invalid JSON Schema, cannot continue\nSyntax errors:\n[ {\n  \"level\" : \"error\",\n  \"schema\" : {\n    \"loadingURI\" : \"#\",\n    \"pointer\" : \"/properties/oneOf\"\n  },\n  \"domain\" : \"syntax\",\n  \"message\" : \"JSON value is of type array, not a JSON Schema (expected an object)\",\n  \"found\" : \"array\"\n} ]",
  "info" : "other messages follow (if any)"
}, {
  "level" : "error",
  "schema" : {
    "loadingURI" : "#",
    "pointer" : "/properties/oneOf"
  },
  "domain" : "syntax",
  "message" : "JSON value is of type array, not a JSON Schema (expected an object)",
  "found" : "array"
} ]
Run Code Online (Sandbox Code Playgroud)

jru*_*ren 46

试试这个:

{
    "description" : "schema validating people and vehicles",
    "type" : "object",
    "oneOf" : [{
        "properties" : {
            "firstName" : {
                "type" : "string"
            },
            "lastName" : {
                "type" : "string"
            },
            "sport" : {
                "type" : "string"
            }
        },
        "required" : ["firstName"]
    }, {
        "properties" : {
            "vehicle" : {
                "type" : "string"
            },
            "price" : {
                "type" : "integer"
            }
        },
        "additionalProperties":false
    }
]
}
Run Code Online (Sandbox Code Playgroud)


Ari*_*ehr 14

oneOf需要在架构内部使用才能工作.

在内部属性中,它就像另一个名为"oneOf"的属性,没有您想要的效果.

  • 那么通过推断"属性"的作用是有意义的,也就是为什么`属性`会为名为`oneOf`的键做出特殊情况?现在我已经想到了它,这种方式很常见.感谢您的解释. (4认同)