新手求助:如何为JSON Schema中的granted与denied数组配置枚举约束
Hey there! Manual JSON Schema tweaks can feel a bit tricky, especially when you need to lock down array values to specific options. Let's walk through creating a schema for your JSON that includes the enum constraints you need for the granted and denied arrays.
Here's the complete, adjusted JSON Schema:
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "iD": { "type": "integer" }, "balance": { "type": "object", "properties": { "currency": { "type": "string" }, "balance": { "type": "number" }, "date": { "type": "string", "format": "date" } }, "required": ["currency", "balance", "date"] }, "Permissions": { "type": "object", "properties": { "granted": { "type": "array", "items": { "type": "string", "enum": ["canLoginWithPassword", "canGame", "canWithdraw", "canDeposit"] } }, "failedConditions": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" }, "description": { "type": "string" }, "details": { "type": "object", "properties": { "reason": { "type": "string" } }, "required": ["reason"] }, "denied": { "type": "array", "items": { "type": "string", "enum": ["canLoginWithPassword", "canGame", "canWithdraw", "canDeposit"] } } }, "required": ["name", "description", "details", "denied"] } } }, "required": ["granted", "failedConditions"] } }, "required": ["iD", "balance", "Permissions"] }
Key parts to note for your enum constraints:
For the
grantedarray:
We define it as an array with"type": "array", then use theitemskeyword to specify that every element in the array must be a string matching one of your allowed permissions. Theenumlist includes all four possible values you mentioned, so any element ingrantedhas to be one of these (you can have one, multiple, or even an empty array by default).For the
deniedarray insidefailedConditions:
The exact same logic applies here. We nest theenumconstraint under theitemsproperty of thedeniedarray, ensuring only your specified permissions are allowed here too.
Extra touches I added:
- Marked required fields with the
requiredkeyword (you can adjust this if some fields are optional) - Added type constraints for all fields (like
iDas integer,dateas ISO date string) to make the schema more robust - Used draft-07 (a widely supported version of JSON Schema)
If you need to enforce a minimum number of items in the arrays (e.g., at least one permission), you can add "minItems": 1 to the array's schema. For example:
"granted": { "type": "array", "minItems": 1, "items": { "type": "string", "enum": ["canLoginWithPassword", "canGame", "canWithdraw", "canDeposit"] } }
内容的提问来源于stack exchange,提问作者Abiodun Adeoye

