如何配置JSON Schema使Avatar仅为false或指定对象类型
Fixing JSON Schema for Avatar: Restrict to Only
false or Valid Object The issue with your original schema is that type: ["object", "boolean"] allows any boolean value (true or false), but you need to lock it down to only false when using the boolean option. Here's how to adjust your schema to enforce this requirement:
const avatarSchema = { "oneOf": [ { "type": "boolean", "const": false }, { "type": "object", "required": ["name", "image"], // Optional: uncomment if these fields are mandatory for the avatar object "additionalProperties": false, "properties": { "name": { "type": "string" }, "image": { "type": "string", "format": "url" } } } ] };
Key Changes Explained:
oneOfkeyword: This tells the validator that the value must match exactly one of the subschemas defined inside it—perfect for your "either false or object" use case.- Boolean constraint: The first subschema uses
const: falsealongsidetype: "boolean"to explicitly restrict the boolean option to onlyfalse(no more allowing invalidtruevalues). - Object validation: The second subschema retains your original object structure. I added a note about
required: ["name", "image"]—if those fields are mandatory for a visible avatar, uncommenting this line will ensure they're always present (your original schema had an emptyrequiredarray, so adjust based on your actual needs).
This setup will now correctly reject true as a valid Avatar value, while still accepting either false (to hide the avatar) or a properly structured object with name and image fields.
内容的提问来源于stack exchange,提问作者pedalpete
相关产品推荐
相关产品推荐

