blob: f439bcea1e94067fbee4bd5a96e0ed1f1d91a735 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Safely stringifies an object to JSON, handling circular references by replacing them with [Circular].
*
* @param obj - The object to stringify
* @param space - Optional space parameter for formatting (defaults to no formatting)
* @returns JSON string with circular references replaced by [Circular]
*/
export function safeJsonStringify(
obj: unknown,
space?: string | number,
): string {
const seen = new WeakSet();
return JSON.stringify(
obj,
(key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular]';
}
seen.add(value);
}
return value;
},
space,
);
}
|