@FahadM to JavaScriptEnglish • 5 days ago

How do you serialize a JavaScript object into a JSON string with JSON.stringify()?

message-square
0
1
How do you serialize a JavaScript object into a JSON string with JSON.stringify()?
@FahadM to JavaScriptEnglish • 5 days ago

To convert a JavaScript object into a JSON string, call JSON.stringify(value, replacer, space) and guard against non-serializable values, circular references, or undefined return values. JSON.stringify() serializes enumerable own string-keyed properties into valid JSON text while omitting functions, symbol keys, and undefined properties (or converting undefined top-level values to undefined, not a string).


1. Basic and Pretty-Printed Serialization with JSON.stringify()

Pass a plain object as the first argument to JSON.stringify(), optionally provide a space indentation value (2 or 4) for human-readable output, and wrap the call in try / catch so circular references or custom .toJSON() errors are handled safely:

// Serialize a JavaScript object into a JSON string with optional indentation
function serializeObjectToJson(data, { pretty = false, indent = 2 } = {}) {
  if (data === null || typeof data !== "object") {
    return JSON.stringify(data);
  }

  const seen = new WeakSet();

  const detectCircular = (_key, value) => {
    if (typeof value === "object" && value !== null) {
      if (seen.has(value)) {
        throw new TypeError("Cannot serialize object containing a circular reference.");
      }
      seen.add(value);
    }
    return value;
  };

  const spacing = pretty ? indent : undefined;
  return JSON.stringify(data, detectCircular, spacing);
}

// Example usage:
const payload = Object.freeze({ id: 42, role: "editor", tags: ["js", "api"] });
console.log(serializeObjectToJson(payload, { pretty: true, indent: 2 }));
  • Pretty-printing with space: Passing 2 formats keys and nested structures across lines for logs or debugging, while omitting space produces compact JSON.
  • Circular reference guard: Tracking visited objects in a WeakSet catches self-referential cycles before JSON.stringify() throws a TypeError.

2. Filtering or Transforming Fields via a replacer Function

Provide a replacer(key, value) callback to redact sensitive fields, convert special types like BigInt or Map, or normalize values without mutating the original object:

// Serialize an object while redacting secret keys and formatting BigInt values
function serializeSanitizedPayload(inputObj, redactedKeys = ["password", "token"]) {
  if (inputObj === null || typeof inputObj !== "object" || Array.isArray(inputObj)) {
    throw new TypeError("Expected a non-null plain object to serialize.");
  }

  const secretSet = new Set(Array.isArray(redactedKeys) ? redactedKeys : []);

  return JSON.stringify(inputObj, (key, value) => {
    if (key && secretSet.has(key)) {
      return "[REDACTED]";
    }
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  });
}

// Example usage:
const userRecord = { username: "ali", token: "secret_123", balance: 500n };
console.log(serializeSanitizedPayload(userRecord)); // '{"username":"ali","token":"[REDACTED]","balance":"500"}'
  • Non-mutating transformation: The replacer adjusts the serialized output on the fly without altering userRecord.
  • Handles BigInt safely: Standard JSON.stringify() throws on BigInt unless converted (such as .toString()).

3. Common Traps to Avoid

Serializing JavaScript objects with JSON.stringify() often hits a few subtle pitfalls:

  • **Circular references throwing