JSON Schema - 根据另一个字段的值需要指定字段 [英] JSON Schema - specify field is required based on value of another field
问题描述
必需的 code>某些字段的属性。
我目前最好的尝试(不起作用)应该给你一些我以后的想法。我想要默认值,在另一个字段有一个特定的值时是可选的。
{
description :a address ...,
type:object,
properties:{
postcode:{
type:string ,
//默认情况下需要邮政编码
required:true,
//如果国家是新西兰,则不需要邮政编码
dependencies:{
country:{
enum:[NZ,NZL,NEW ZEALAND]
},
postcode:{
required:false
}
}
},
country:{
type:string,
enum [
//各种国家代码和名称...
],
默认:AUS
}
}
}
解决方案的草稿。由于您拥有允许的国家/地区的完整列表,因此您可以执行以下操作:
{
type :[
{
title:New Zealand(no postcode),
type:object,
properties:{
国家:{enum:[NZ,NZL,NEW ZEALAND]}
}
},
{
title:其他国家(需要邮政编码),
type:object,
properties:{
country:{enum:[< other other countries>]} ,
postcode:{required:true}
}
}
],
properties:{
country
type:string,
default:AUS
},
postcode:{
type:string
}
}
}
所以你实际上定义了两个您的模式的子类型,一个用于需要邮政编码的国家,另一个用于不需要邮政编码的国家。
编辑 - v4等效非常相似。只需将顶级类型
数组重命名为oneOf
。
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"
}
}
}
解决方案 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"
.
这篇关于JSON Schema - 根据另一个字段的值需要指定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!