简体   繁体   中英

JSON-Schema draft-04 - OneOf with required

I have an API route that validate the json schema before to handle the logic.

This route can create 2 types of "articles" based on the JSON sent. I used OneOf to check if the schema correspond to one of this 2 types.

{
    "type": "object",
    "oneOf": [{
        "properties": {
            "name": {
                "type": "string",
            },
            "description": {
                "type": "string"
            }
        }
    }, {
        "properties": {
            "author": {
                "type": "string",
            },
            "editor": {
                "type": "string"
            }
        },
        "required":["author", "editor"]
    }]
} 

  • So the first type can have a name and description, but this fields are not required.

  • The second type required to have an author and editor .

What happend if a JSON schema is sent with only author field? ( editor is empty)

Thanks for your responses.

By the definition of the oneOf keyword

To validate against oneOf, the given data must be valid against exactly one of the given subschemas.

In the way your schema is defined, an object containing only an "author" property will always validate, because of the fist oneOf definition can be translated as:

An object with any set of properties is valid, but if the object contains "name" and "description" properties, they must both be of a string type.

As you can see, an object containing only an "author" property is perfectly valid by this definition.

In reality, any given object will only be validated against the second oneOf definition (author, editor) if the given object contains "name" and/or "description" properties and they are not strings.

This is a good reference for learning JSON Schema https://spacetelescope.github.io/understanding-json-schema/

And this is a good JSON Schema validator http://www.jsonschemavalidator.net

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM