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
963 views
in Technique[技术] by (71.8m points)

dependencies - JSON Schema - specify field is required based on value of another field

Wondering if this is possible with schema draft 03. I've gotten dependencies working elsewhere, I think there is possibly just some creative use of them required in order to use them for specifying the required property of some field.

My current best attempt (which doesn't work) should give you some idea of what I'm after. I want a value required by default, and optional when another field has a particular value.

{
    "description"   : "An address...",
    "type" : "object",
    "properties" : {
        "postcode": {
            "type" : "string",
            // postcode should be required by default
            "required" : true,      
            // postcode shouldn't be required if the country is new zealand 
            "dependencies" : {
                "country" : {
                    "enum" : ["NZ", "NZL", "NEW ZEALAND"]
                },
                "postcode" : {
                    "required" : false      
                }
            }
        },
        "country": {
            "type" : "string",
            "enum" : [
                // various country codes and names...
            ],
            "default" : "AUS"
        }
    }
}
question from:https://stackoverflow.com/questions/9029524/json-schema-specify-field-is-required-based-on-value-of-another-field

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

1 Reply

0 votes
by (71.8m points)

This is definitely possible with version 3 of the draft. Since you have a complete list of allowed countries, then you could do something like this:

{
    "type": [
        {
            "title": "New Zealand (no postcode)",
            "type": "object",
            "properties": {
                "country": {"enum": ["NZ", "NZL", "NEW ZEALAND"]}
            }
        },
        {
            "title": "Other countries (require postcode)",
            "type": "object",
            "properties": {
                "country": {"enum": [<all the other countries>]},
                "postcode": {"required": true}
            }
        }
    ],
    "properties": {
        "country": {
            "type" : "string",
            "default" : "AUS"
        },
        "postcode": {
            "type" : "string"
        }
    }
}

So you actually define two sub-types for your schema, one for countries that require a postcode, and one for countries that do not.

EDIT - the v4 equivalent is extremely similar. Simply rename the top-level "type" array to "oneOf".


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

...