Skip to content

normalizeJSONValue

Guarantees a valid JSONValue or returns null.

This helper determines whether an unknown value can be represented as JSON without coercion, mutation, or loss of information. It strictly mirrors the JSON data model and treats null as a first-class value, not a failure signal.

Use this helper when you need to ensure a value is structurally JSON-safe before serialization, persistence, hashing, or transport.

Signature

function normalizeJSONValue(value: unknown): JSONValue | null

Parameters

Name Data type Description
value unknown A value that may represent a TCP port number

Returns

One of:

  • A valid JSONValue
  • null: If the value cannot be represented as JSON.

Important null is returned both when the input is the JSON value null and when normalization fails. Failure is detected internally by comparing the normalized result with the original input.

Behavior

  • Accepts JSON primitives:
  • null.
  • boolean.
  • string.
  • Accepts finite numbers only: NaN, Infinity, and -Infinity are rejected.
  • Accepts arrays whose elements recursively satisfy JSONValue.
  • Accepts plain objects whose properties recursively satisfy JSONValue.
  • Rejects all other types:
  • undefined.
  • Functions.
  • Symbols.
  • BigInt.
  • Class instances.
  • Never throws and never mutates input.

Examples

normalizeJSONValue(null)
// null

normalizeJSONValue(true)
// true

normalizeJSONValue({ a: 1, b: [true, null] })
// { a: 1, b: [true, null] }

normalizeJSONValue([1, 2, "three"])
// [1, 2, "three"]

normalizeJSONValue(NaN)
// null

normalizeJSONValue({ a: undefined })
// null

normalizeJSONValue(() => {})
// null

Notes

  • This helper does not stringify or parse JSON
  • No coercion is performed
  • The output is guaranteed to conform to:

ts export type JSONValue = | null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };

  • Behavior intentionally matches what JSON.stringify would reject, but without side effects