JSON Schema是否原生支持布尔属性的自定义真假命名?
The Problem
Let me break down your issue first: Your original JSON Schema has a conflict that’s triggering the validation error. You defined theme as a boolean type but paired it with an enum of string values (["Light", "Dark"]). Boolean types in JSON Schema only accept true/false as valid inputs, so when your form submits "Light" or "Dark", schema validation fails before the request even reaches your backend.
You’re currently working around this by switching the type to string and converting the value on the backend—but you want to know if there’s a native JSON Schema way to map boolean values to custom display names.
The Answer
Standard JSON Schema doesn’t have a built-in keyword specifically for mapping boolean true/false to custom string labels. However, there are two clean, schema-native approaches to get the behavior you want without changing the type to string:
Use
oneOf+const+title(Fully Standard Compliant)
This is the official, standards-aligned way to define boolean options with custom display names. Eachconstentry defines a valid boolean value, and thetitlefield sets the human-readable label that form generators should render:"properties": { "theme": { "title": "Theme", "type": "boolean", "oneOf": [ { "const": true, "title": "Light" }, { "const": false, "title": "Dark" } ] } }Most modern form generators (like react-jsonschema-form, JSON Forms) will pick up the
titlevalues and render "Light"/"Dark" as selectable options, while submittingtrue/falseunder the hood—perfect for matching your database’s boolean storage format.Use
enumNames(Library-Specific Extension)
Some JSON Schema form libraries support a non-standardenumNameskeyword that mapsenumvalues to display labels. If your tool supports this, you can keep thebooleantype and define:"properties": { "theme": { "type": "boolean", "title": "Theme", "enum": [true, false], "enumNames": ["Light", "Dark"] } }Just note:
enumNamesisn’t part of the official JSON Schema specification, so this only works if your form generator explicitly supports it.
Comparing to Your Current Workaround
Your current approach (switching to string type and converting on the backend) is totally valid, but using the oneOf method above keeps your schema aligned with the actual data type stored in your database, eliminates backend conversion logic, and stays within standard JSON Schema rules.
内容的提问来源于stack exchange,提问作者Ivan T.

