Stanimirovv
Stanimirovv

Reputation: 3172

Json Schema example for oneOf objects

I am trying to figure out how oneOf works by building a schema which validates two different object types. For example a person (firstname, lastname, sport) and vehicles (type, cost).

Here are some sample objects:

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

{"vehicle":"car", "price":20000}

The question is what have I done wrongly and how can I fix it. Here is the schema:

{
    "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"} 
        }
     ]
   }
}

When I try to validate it in this parser:

https://json-schema-validator.herokuapp.com/

I get the following error:

   [ {
  "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"
} ]

Upvotes: 62

Views: 123666

Answers (2)

jruizaranguren
jruizaranguren

Reputation: 13607

Try this:

{
  "description": "schema validating people and vehicles",
  "type": "object",
  "oneOf": [
    {
      "type": "object",
      "properties": {
        "firstName": {
          "type": "string"
        },
        "lastName": {
          "type": "string"
        },
        "sport": {
          "type": "string"
        }
      }
    },
    {
      "type": "object",
      "properties": {
        "vehicle": {
          "type": "string"
        },
        "price": {
          "type": "integer"
        }
      },
      "additionalProperties": false
    }
  ]
}

Upvotes: 85

Arian Kiehr
Arian Kiehr

Reputation: 451

oneOf need to be used inside a schema to work.

Inside properties, it's like another property called "oneOf" without the effect you want.

Upvotes: 31

Related Questions