Skip to content

Instantly share code, notes, and snippets.

@zakgrant
Created July 1, 2013 11:15
Show Gist options
  • Select an option

  • Save zakgrant/5900025 to your computer and use it in GitHub Desktop.

Select an option

Save zakgrant/5900025 to your computer and use it in GitHub Desktop.
This is how to represent an object that can have multiple types within a JSON Schema
{
"$schema": "http://json-schema.org/draft-03/schema#",
"type": [
{
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
},
{
"type": "string",
"pattern": "^.+@.+\\..+$"
}
]
}
@zakgrant

zakgrant commented Jul 1, 2013

Copy link
Copy Markdown
Author

v4 way...

{ 
    "anyOf": [ 
        { 
            "type": "number", 
            "minimum": 0, 
            "exclusiveMinimum": true 
        }, 
        { 
            "type": "string", 
            "pattern": "^.+@.+\\..+$" 
        } 
    ] 
} 

@geraintluff

Copy link
Copy Markdown

For v4, I'd probably use "oneOf" for preference in this case.

It makes no actual difference to validation, because the two schemas are incompatible - however, explicitly stating that they should be exclusive (by using "oneOf") makes it slightly more intuitive to read.

@geraintluff

Copy link
Copy Markdown

Using "oneOf" also gives more of a hint for automated processors, as well as human readers. For example, if you paste this schema:

{ 
    "oneOf": [ 
        {
            "title": "Number",
            "type": "number", 
            "minimum": 0, 
            "exclusiveMinimum": true 
        }, 
        {
            "title": "String",
            "type": "string"
        } 
    ] 
}

into this page (selecting the "Editable" option), then the interface gives you a nice drop-down for the different schema options.

However, if you replace "oneOf" with "anyOf", then the interface doesn't know the schemas are exclusive, so it presents a multiple-select instead (hidden behind a button), which isn't quite as intuitive.

@zakgrant

zakgrant commented Jul 2, 2013

Copy link
Copy Markdown
Author

@geraintluff thanks for your input, that is more intuitive especially in this context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment