Skip to content
MINH VO A working notebook
by an engineer in Vietnam
Foundation8 min read

Absent, null and empty values in a JSON request

Separate omitted properties, explicit null and empty strings in a JSON update contract, then validate each state without accidental truthiness defaults.

Olive and charcoal server components connected on a warm beige background

An omitted JSON property, a property set to null and a property containing an empty string are different inputs. For a backend developer implementing account updates, preserve those differences until the API contract decides what each means. Using one truthiness check for all three can turn an intended clear operation into “leave unchanged,” or erase a value the caller never meant to touch.

JSON Schema’s object reference distinguishes property presence from the value’s type. A required property must be present. It can still contain null if the property’s schema allows null. Conversely, an optional property can reject null whenever it is present.

Write the three requests before the handler

Consider a hypothetical account with displayName: "Minh". A partial-update endpoint might define these requests:

{}
{"displayName": null}
{"displayName": ""}

One possible contract says that omission keeps the current value, null clears an optional display name and an empty string is invalid. Another contract can accept an empty string as a real value. Either is possible, but the client and server must agree before a form’s serialization code can be correct.

A text input usually gives JavaScript a string, including an empty string after the user deletes its contents. If the server uses null to clear a field, the client needs an explicit mapping for the clear action. Do not assume an untouched field and a deliberately cleared field produce distinguishable JSON automatically.

The example’s behavior is application-defined. RFC 5789 defines the PATCH method, while the patch document’s media type determines how its instructions apply. A plain JSON object does not inherit universal “omit means keep” semantics merely because it is sent with PATCH.

Presence and type are separate schema rules

For a creation request that requires a non-null display name, a schema can express both requirements:

{
  "type": "object",
  "properties": {
    "displayName": {"type":"string", "minLength":1, "maxLength":80}
  },
  "required": ["displayName"],
  "additionalProperties": false
}

Removing displayName from required makes the property optional, but it does not permit null. To allow null explicitly, the property’s type can include both string and null, with the remaining string constraints applied according to JSON Schema’s rules.

A default annotation is also not a universal instruction to mutate the request. Some validation tools offer options that apply defaults, while others simply validate and report annotations. Document any defaulting behavior your implementation enables, including whether it applies only to missing properties or to explicit null as well.

Three account update inputs take different branches: omitted preserves a value, null clears it, and an empty string is rejected under this example contractView full-size image ↗

The branches are a policy choice for this endpoint. Copying the same branches into another field without checking its meaning can create a new bug.

Avoid truthiness as a presence test

A handler such as if (body.displayName) updateName(body.displayName) ignores both null and an empty string. It also makes the control flow depend on JavaScript truthiness rather than the documented input states. For other fields, valid values such as zero or false disappear through the same pattern.

Test property ownership explicitly when omission has meaning. After validating the object, Object.hasOwn(body, 'displayName') distinguishes an absent property from a present property whose value is null. This also avoids relying on a prototype method supplied by untrusted object content.

Do not use the in operator without considering inherited properties if your handler can receive objects beyond ordinary parsed JSON. A request pipeline can transform data or introduce custom objects. Validate and normalize at one known boundary so the persistence layer receives a deliberately constructed write model.

Serialization can also erase an internal distinction before the request leaves the client. In ordinary JavaScript object serialization, an undefined property is omitted by JSON.stringify, while an explicit null is retained. Arrays have different handling for undefined entries. Inspect the actual serialized request when debugging presence rules; a debugger showing a JavaScript object is not evidence of the bytes sent over HTTP.

Persistence can collapse states too early

A relational column usually stores a value or SQL NULL. The request’s “not supplied” state is an instruction about whether to write that column, not a third value that must be stored. Build the update from the contract: omit the column from the write, assign NULL, or assign the validated string.

An ORM helper that maps every undefined property to a database default may behave differently from one that ignores undefined. Check its exact update semantics. Passing the request object directly into persistence makes those library defaults part of the public API, often unintentionally.

When several fields participate in one rule, validate the resulting state too. An update that omits startDate while clearing endDate may be structurally valid but invalid for the account’s subscription policy. Fetch or lock the relevant current state under the operation’s concurrency contract before deciding that the final combination is allowed.

Convert the validated distinction into an explicit change

Represent the requested action before constructing an ORM update. This small function accepts only the one-field contract used here and returns keep, clear or set. It runs after JSON parsing and is intentionally independent of any particular database library. Errors are symbolic examples for the application’s public error mapper, not complete HTTP responses.

function displayNameChange(body) {
  if (body === null || typeof body !== 'object' || Array.isArray(body)) {
    throw new Error('invalid_object');
  }
  if (Object.keys(body).some(key => key !== 'displayName')) {
    throw new Error('unknown_field');
  }
  if (!Object.hasOwn(body, 'displayName')) return { kind: 'keep' };
  const value = body.displayName;
  if (value === null) return { kind: 'clear' };
  if (typeof value !== 'string') throw new Error('invalid_display_name');
  const length = [...value].length;
  if (length < 1 || length > 80) throw new Error('invalid_display_name');
  return { kind: 'set', value };
}

The length rule counts Unicode code points, not UTF-8 bytes or user-perceived grapheme clusters. It preserves the supplied string, including spaces. If trimming or a rule against whitespace-only values belongs to the product, add it deliberately at this boundary and align the schema with it. The function does not silently turn a value into a different display name.

For a current value of Minh, an empty object yields keep, explicit null yields clear, and a nonempty valid string yields set with that string. An empty string, a number and an extra role field are rejected. A persistence adapter can now omit the column for keep, assign SQL NULL for clear and bind the exact validated value for set. This avoids depending on whether a particular ORM ignores undefined, treats it as a default or rejects it.

In the executed JavaScript fixture, these branches were checked without mutating the input objects. The fixture also applied the resulting change to an in-memory account snapshot: keep preserved Minh, clear stored null and set stored the chosen name. That is a test of the write model, not evidence that an ORM or SQL database has the same behavior. Repeat the matrix against the actual adapter before claiming persistence correctness.

An own undefined property is rejected on a direct call, but JSON.stringify omits it so parsing the JSON before the same call yields keepView full-size image ↗

Observe serialization before assigning meaning

JavaScript can hold undefined, but JSON has no undefined value. Compare these two wire representations using ECMAScript’s JSON serialization rules:

JSON.stringify({ displayName: undefined }); // '{}'
JSON.stringify({ displayName: null });      // '{"displayName":null}'
JSON.stringify([undefined]);               // '[null]'

Passing an own displayName property with value undefined directly to the function raises an invalid-value error. Serializing that same object and parsing the JSON first produces an empty object, so the function returns keep. The two paths are different because serialization removed the property. A unit test that bypasses the client serializer can therefore miss a real clear-versus-keep bug.

The array example is another reason to examine the actual bytes instead of generalizing an object rule to every JSON container. Undefined array elements are represented as null in this ordinary serialization path. Custom toJSON methods and replacers can introduce additional transformations, so a shared helper should have a documented scope. The examples here use ordinary objects and arrays without those hooks.

The JSON Schema annotation reference explicitly separates default annotations from validation-time filling of missing values. If a library adds its own default-application mode, test that configured mode separately. An explicit clear action should not disappear merely because another layer equates null, absence and a fallback value.

Test a small input matrix

For each mutable field, test absence, null, an empty value and an ordinary valid value. Add type errors and boundary lengths where they matter. Record both the response and the stored result, because an endpoint can return success while silently skipping an intended clear.

Repeat the same cases through the actual frontend serialization path. A browser form, a mobile client and an SDK may each encode optional values differently. A shared schema helps only if each client uses it with compatible settings.

Keep separate schemas for creation, replacement and partial updates when their presence rules differ. Reusing one class with every field optional can make code look concise while losing the ability to express what the caller must provide for each operation.

Sources & further reading

  1. JSON Schema, object reference
  2. RFC 5789, PATCH method
  3. ECMAScript, JSON.stringify and JSON serialization
  4. JSON Schema, annotations and default
← Back to the journal
All notes

Illustration

100%