TS-Scribe - v1.2.0
    Preparing search index...

    Function jsonByteSize

    • Returns the UTF-8 byte size of a value as it would appear when JSON-serialized.

      The accuracy parameter controls the precision/speed trade-off:

      • 'exact' (default) — Serializes the value via safeJsonStringify and measures the resulting string. Handles every edge case (circular references, throwing getters, toJSON(), BigInt, etc.) at the cost of O(n) memory for the intermediate JSON string.
      • 'fast' — Recursive walk using real UTF-8 byte counts plus JSON escape overhead. Calls toJSON() and skips throwing getters. Does not protect against circular references.
      • 'estimate' — Like 'fast' but uses character count (string.length) instead of UTF-8 byte counts, and does not call toJSON(). Fastest option but may undercount multi-byte Unicode strings or strings with many escape sequences.

      Parameters

      • value: unknown

        Any value to measure. Primitives, objects, arrays, null, and undefined are all accepted.

      • Optionalaccuracy: JsonByteSizeAccuracy = 'exact'

        Controls the precision/speed trade-off. Defaults to 'exact'.

      Returns number

      The UTF-8 byte length of the JSON-serialized value.

      // Basic usage — measures the exact byte size of a serialized object
      jsonByteSize({ name: 'Alice', age: 30 }); // Returns 22
      // Fast mode — same result for ASCII data, avoids allocating the full JSON string
      jsonByteSize({ name: 'Alice', age: 30 }, 'fast'); // Returns 22
      // Multi-byte Unicode — 'exact' and 'fast' agree, 'estimate' undercounts
      jsonByteSize('🎉', 'exact'); // Returns 6 (2 quotes + 4 UTF-8 bytes)
      jsonByteSize('🎉', 'fast'); // Returns 6
      jsonByteSize('🎉', 'estimate'); // Returns 4 (undercounts — emoji is 2 JS chars but 4 UTF-8 bytes)
      // Payload size guard — 'fast' avoids allocating a full JSON string
      const MAX_BYTES = 1024 * 256; // 256 KB
      if (jsonByteSize(payload, 'fast') > MAX_BYTES) {
      throw new Error('Payload too large');
      }