定义可维护的JSON Schema:限制账户角色为OWNER和CHARGE_TO
Solution: Enforce OWNER & CHARGE_TO Accounts with Maintainable JSON Schema
Got it, let's build a robust, easy-to-update JSON Schema that meets your requirements. The goal is to lock in the mandatory roles while making it trivial to add new ones later.
The JSON Schema
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "accounts": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "role": { "$ref": "#/$defs/allowedRoles" } }, "required": ["id", "role"], "additionalProperties": false }, // Ensure every required role is present in the array "allOf": [ { "contains": { "properties": { "role": { "const": "OWNER" } } } }, { "contains": { "properties": { "role": { "const": "CHARGE_TO" } } } } ], "minItems": 2 // Enforces at least two entries (matches the two mandatory roles) } }, "required": ["accounts"], "$defs": { "allowedRoles": { "enum": ["OWNER", "CHARGE_TO"], "description": "Only these roles are permitted in the accounts list" } }, "additionalProperties": false }
Why this is maintainable:
- Centralized role control: All permitted roles live in
$defs.allowedRoles—add a new role here first. - Modular required checks: Each
containsclause guarantees a specific role exists. Adding a new mandatory role only requires adding one more{ "contains": { "properties": { "role": { "const": "NEW_ROLE" } } } }to theallOfarray.
Valid JSON Examples
Example 1: Separate OWNER and CHARGE_TO accounts
{ "accounts": [ { "id": "acc-owner-001", "role": "OWNER" }, { "id": "acc-charge-001", "role": "CHARGE_TO" } ] }
Example 2: Single account assigned both roles (if your use case allows it)
{ "accounts": [ { "id": "acc-combined-001", "role": "OWNER" }, { "id": "acc-combined-001", "role": "CHARGE_TO" } ] }
Invalid JSON Examples
Missing the OWNER role
{ "accounts": [ { "id": "acc-charge-001", "role": "CHARGE_TO" } ] }
Includes an unauthorized role ("VIEWER")
{ "accounts": [ { "id": "acc-owner-001", "role": "OWNER" }, { "id": "acc-charge-001", "role": "CHARGE_TO" }, { "id": "acc-view-001", "role": "VIEWER" } ] }
Missing the CHARGE_TO role
{ "accounts": [ { "id": "acc-owner-001", "role": "OWNER" } ] }
内容的提问来源于stack exchange,提问作者Vinni
相关产品推荐
相关产品推荐

