Boolean and Null Types in JSON Schema Generation

Understand how JSON Schema represents boolean and null types, and learn when to use nullable fields in your generated schemas for robust API validation.

Basic Types

Detailed Explanation

Handling Booleans and Null in Generated Schemas

Boolean and null are the simplest JSON types, yet they appear in almost every real-world schema. Understanding how the generator handles them — and when to adjust — is essential.

Boolean Generation

When the generator sees true or false, it outputs:

{ "isActive": { "type": "boolean" } }

This accepts only the literal JSON values true and false. The strings "true" and "false" will fail validation, as will numbers like 0 and 1. This strictness is intentional — JSON Schema enforces type safety.

Null Generation

A null value in the sample produces:

{ "deletedAt": { "type": "null" } }

However, a field typed as only null is rarely useful in practice. What you usually want is a nullable field — one that accepts either its primary type or null.

Making Fields Nullable

JSON Schema supports two approaches for nullable fields:

Type array (preferred in Draft 2020-12):

{
  "deletedAt": {
    "type": ["string", "null"],
    "format": "date-time"
  }
}

Using anyOf:

{
  "deletedAt": {
    "anyOf": [
      { "type": "string", "format": "date-time" },
      { "type": "null" }
    ]
  }
}

Both accept either a valid date-time string or null. The type-array syntax is more concise, while anyOf gives you finer control when each branch has different constraints.

Generator Behavior with Mixed Samples

If you provide multiple sample objects — one with a string value for deletedAt and another with null — a smart generator will emit the type-array form automatically. When working with a single sample, you may need to adjust the generated schema manually.

Best Practices

  • Avoid type: "null" alone unless the field truly should never hold a value.
  • Prefer the type-array syntax for clarity: ["string", "null"].
  • Document nullable fields with a description so consumers know when null is expected (e.g., "null when the record has not been soft-deleted").

Use Case

Use boolean and null types for feature flags, soft-delete timestamps, opt-in toggles, and any API field that toggles between a meaningful value and an explicit absence of value.

Try It — JSON Schema Generator

Open full tool