Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

jsonschema - How to define a JSON schema that requires at least one of many properties

I would like to know if I can define a JSON schema (draft 4) that requires at least one of many properties possible for an object. I already know of allOf, anyOf and oneOf but just can't figure out how to use them in the way I want.

Here are some example JSON to illustrate :

// Test Data 1 - Should pass
{

    "email": "hello@example.com",
    "name": "John Doe"
}
// Test Data 2 - Should pass
{
    "id": 1,
    "name": "Jane Doe"
}
// Test Data 3 - Should pass
{
    "id": 1,
    "email": "hello@example.com",
    "name": "John Smith"
}
// Test Data 4 - Should fail, invalid email
{
    "id": 1,
    "email": "thisIsNotAnEmail",
    "name": "John Smith"
}

// Test Data 5 - Should fail, missing one of required properties
{
    "name": "John Doe"
}

I would like to require at least id or email (also accepting both of them) and still pass validation according to format. Using oneOf fails validation if I provide both (test 3), anyOf passes validation even if one of them is not valid (test 4)

Here is my schema :

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "id": "https://example.com",
    "properties": {
        "name": {
            "type": "string"
        }
    },
    "anyOf": [
        {
            "properties": {
                "email": {
                    "type": "string",
                    "format": "email"
                }
            }
        },
        {
            "properties": {
                "id": {
                    "type": "integer"
                }
            }
        }
    ]
}

Can you help me how to achieve correct validation for my use case ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To require at least one of a set of properties, use required inside a series of anyOf options:

{
    "type": "object",
    "anyOf": [
        {"required": ["id"]},
        {"required": ["email"]}
        // any other properties, in a similar way
    ],
    "properties": {
        // Your actual property definitions here
    }
{

If any of the properties you want is present ("id", "email"), then it will pass the corresponding option in allOf.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...