Reputation: 5736
I need to add an optional property to a JSON schema. This property is of Enum type. I need to set default value in the case the user does not specify this field.
// schema
"properties" : {
"Param" : {
"type" : "string",
"enum" : [ " p1", "p2" ],
"optional" : true,
"default" : "p2",
"required" : true
}
}
If user will not specify "Param" field it should recognize field as "p2"
Upvotes: 7
Views: 18663
Reputation: 1504
The solution is not in the schema but in the parser/compiler; unspecified fields should have the value 0 when transferred to variable.
In this case it would be:
"enum" : [ "p2", "p1" ],
and the equivalent in C would be:
enum {
p2 = 0,
p1 = 1
}
Hope this help.
Upvotes: 0
Reputation: 79
Add null
to the enum
array
More: https://json-schema.org/understanding-json-schema/reference/generic.html#enumerated-values
"properties" : {
"Param" : {
"type" : "string",
"enum" : [ " p1", "p2", null ], // <--
"default" : "p2", // <--
"required" : true
}
}
Upvotes: 7
Reputation: 379
"properties" : {
"Param" : {
"type" : "string",
"enum" : ["p1", "p2"],
"default" : "p2"
}
},
"required" : ["Param"]
Upvotes: -2
Reputation: 13615
As you have put in your example, "default" is a valid json-schema keyword. But its use is up to the schema consumer.
Take into account that json-schema is concerned with data structure definition and validation. In fact this keyword was added after much discussion because it is so common that we want to give a hint to clients of what should be a default value in case they do not want to set one. But, again, it is up to the client to make use this value or not.
Another way to approach your particular case would be to use "oneOf" splitting enum values.
"required" : ["Param"],
"oneOf" : [{
"properties" : {
"Param" : {
"enum" : ["p2"]
}
}
}, {
"properties" : {
"Param" : {
"enum" : ["p1", "p3"]
}
}
}
]
In this case you are telling the client: "at least you must send me "Param" with value "p2".
Finally, you could also add a pre-process step in your server side where you take all missing properties with default value, and add them to json message before validation.
Upvotes: 3