Null Type and Nullable Fields in JSON Schema
Learn how to handle null values and nullable fields in JSON Schema. Understand the difference between null type, missing properties, and empty strings.
JSON Schema
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"middleName": {
"type": ["string", "null"]
},
"deletedAt": {
"type": ["string", "null"],
"format": "date-time"
}
},
"required": ["firstName", "middleName"]
}Test Data
{
"firstName": "Alice",
"middleName": null,
"deletedAt": null
}Detailed Explanation
Handling Null Values in JSON Schema
JSON has a dedicated null type represented by the literal keyword null. In JSON Schema, you can allow a field to accept null alongside other types using a type array.
Nullable Fields with Type Arrays
{
"type": ["string", "null"]
}
This schema accepts both string values like "hello" and the literal null. It rejects numbers, booleans, arrays, and objects.
Null vs. Missing vs. Empty
These three states are fundamentally different in JSON Schema:
| State | JSON | Passes required? |
Passes type: "string"? |
|---|---|---|---|
| Present with value | "Alice" |
Yes | Yes |
| Present as null | null |
Yes | No (unless nullable) |
| Missing entirely | (key absent) | No | N/A (not checked) |
| Empty string | "" |
Yes | Yes |
How the Example Schema Works
The schema models a user record with soft-delete support:
firstNameis a required string that must always have a value —nullis not allowed.middleNameis required but nullable. The user must explicitly send this field, but its value can benull(for people without a middle name) or a string.deletedAtis an optional, nullable date-time string. When the record is active, this isnull. When soft-deleted, it holds an ISO 8601 timestamp.
The test data passes validation: "Alice" is a string, null satisfies ["string", "null"], and deletedAt (also null) satisfies the same union type.
Draft Differences
In Draft 2020-12 and Draft 7, nullable fields use type arrays: "type": ["string", "null"]. The OpenAPI 3.0 ecosystem introduced a separate nullable: true keyword, but this is not part of the JSON Schema specification — it is an OpenAPI extension. OpenAPI 3.1 aligns with JSON Schema Draft 2020-12 and drops nullable in favor of type arrays.
Best Practices
- Prefer
nullover missing keys when you want to distinguish "not provided" from "explicitly empty." This makes your API contract clearer. - Combine with
required: Making a nullable field required forces clients to acknowledge the field exists, even if the value isnull. - Document intent: Use the
descriptionkeyword to explain why a field is nullable, so API consumers understand the semantics.
Use Case
Use nullable types for database-backed APIs where columns allow NULL values, soft-delete timestamps, optional relationship fields, and any scenario where the absence of a meaningful value must be explicitly represented rather than omitted.