Like JSON.stringify, but doesn't blow up on circular refs.
npx @tessl/cli install tessl/npm-json-stringify-safe@5.0.00
# JSON Stringify Safe
1
2
JSON Stringify Safe provides a safe alternative to JSON.stringify that handles circular references gracefully instead of throwing errors. It offers the same API as the native JSON.stringify function but includes an additional cycleReplacer parameter for customizing how circular references are handled.
3
4
## Package Information
5
6
- **Package Name**: json-stringify-safe
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install json-stringify-safe`
10
11
## Core Imports
12
13
```javascript
14
var stringify = require('json-stringify-safe');
15
```
16
17
ES Modules (if bundled appropriately):
18
19
```javascript
20
import stringify from 'json-stringify-safe';
21
```
22
23
## Basic Usage
24
25
```javascript
26
var stringify = require('json-stringify-safe');
27
28
// Basic usage - handles circular references automatically
29
var circularObj = {};
30
circularObj.circularRef = circularObj;
31
circularObj.list = [circularObj, circularObj];
32
33
console.log(stringify(circularObj, null, 2));
34
// Output:
35
// {
36
// "circularRef": "[Circular ~]",
37
// "list": [
38
// "[Circular ~]",
39
// "[Circular ~]"
40
// ]
41
// }
42
```
43
44
## Capabilities
45
46
### String Conversion with Circular Reference Handling
47
48
Main stringification function that safely converts objects to JSON strings without throwing on circular references.
49
50
```javascript { .api }
51
/**
52
* Like JSON.stringify, but doesn't throw on circular references
53
* @param {any} obj - The object to stringify
54
* @param {function|array} [replacer] - JSON.stringify replacer parameter
55
* @param {number|string} [spaces] - JSON.stringify spaces parameter for formatting
56
* @param {function} [cycleReplacer] - Custom function to handle circular references
57
* @returns {string} JSON representation of the object
58
*/
59
function stringify(obj, replacer, spaces, cycleReplacer);
60
```
61
62
**Usage Examples:**
63
64
```javascript
65
var stringify = require('json-stringify-safe');
66
67
// Basic circular reference handling
68
var obj = { name: "Alice" };
69
obj.self = obj;
70
stringify(obj);
71
// Result: '{"name":"Alice","self":"[Circular ~]"}'
72
73
// With custom cycle replacer
74
var obj = { name: "Alice" };
75
obj.self = obj;
76
stringify(obj, null, null, function(key, value) {
77
return '[REMOVED]';
78
});
79
// Result: '{"name":"Alice","self":"[REMOVED]"}'
80
81
// With formatting and standard replacer
82
var obj = { name: "Alice", age: 25 };
83
obj.self = obj;
84
stringify(obj, function(key, value) {
85
return typeof value === 'string' ? value.toUpperCase() : value;
86
}, 2);
87
// Result: formatted JSON with "ALICE" instead of "Alice"
88
89
// Pruning cycles (return undefined)
90
var obj = { name: "Alice" };
91
obj.self = obj;
92
stringify(obj, null, null, function() {
93
return undefined;
94
});
95
// Result: '{"name":"Alice"}' (self property omitted)
96
```
97
98
### Serializer Function Generator
99
100
Returns a serializer function that can be used directly with JSON.stringify.
101
102
```javascript { .api }
103
/**
104
* Returns a serializer that can be used elsewhere with JSON.stringify
105
* @param {function|array} [replacer] - JSON.stringify replacer parameter
106
* @param {function} [cycleReplacer] - Custom function to handle circular references
107
* @returns {function} A serializer function compatible with JSON.stringify
108
*/
109
stringify.getSerialize = function(replacer, cycleReplacer);
110
```
111
112
**Usage Examples:**
113
114
```javascript
115
var stringify = require('json-stringify-safe');
116
117
// Use with JSON.stringify directly
118
var obj = { a: "b" };
119
obj.circularRef = obj;
120
obj.list = [obj, obj];
121
122
var serializer = stringify.getSerialize();
123
var json = JSON.stringify(obj, serializer, 2);
124
// Result: formatted JSON with circular references handled
125
126
// With custom cycle replacer
127
var serializer = stringify.getSerialize(null, function(key, value) {
128
return null;
129
});
130
var json = JSON.stringify(obj, serializer);
131
// Result: '{"a":"b","circularRef":null,"list":[null,null]}'
132
```
133
134
**Important Note:** The function returned from `getSerialize` is stateful and should not be reused. Create a new serializer for each stringification operation.
135
136
## Types
137
138
### Cycle Replacer Function
139
140
```javascript { .api }
141
/**
142
* Function called when a circular reference is detected
143
* @param {string} key - The property key where the circular reference was found
144
* @param {any} value - The circular reference value
145
* @returns {any} Replacement value for the circular reference
146
*/
147
function cycleReplacer(key, value);
148
```
149
150
## Circular Reference Behavior
151
152
### Default Behavior
153
154
- **Root circular references**: Replaced with `"[Circular ~]"`
155
- **Nested circular references**: Replaced with `"[Circular ~.path.to.object]"` showing the path to the original object
156
- **Array circular references**: Show index-based paths like `"[Circular ~.children.0]"`
157
158
### Custom Cycle Handling
159
160
The `cycleReplacer` function receives:
161
- `key`: The property name where the circular reference was detected
162
- `value`: The actual circular reference object
163
- `this`: The parent object containing the circular reference
164
165
Return values:
166
- **Any value**: Replaces the circular reference with that value
167
- **`null`**: Explicitly sets the property to null
168
- **`undefined`**: Removes the property from the output entirely
169
170
### Path Format Examples
171
172
```javascript
173
var obj = { name: "Alice", child: { name: "Bob" } };
174
obj.child.parent = obj;
175
stringify(obj);
176
// Result includes: "parent": "[Circular ~]"
177
178
var obj = { users: [{ name: "Alice" }] };
179
obj.users[0].root = obj;
180
stringify(obj);
181
// Result includes: "root": "[Circular ~]"
182
183
obj.users[0].self = obj.users[0];
184
stringify(obj);
185
// Result includes: "self": "[Circular ~.users.0]"
186
```
187
188
## Error Conditions
189
190
- **TypeError**: Thrown if the `cycleReplacer` function returns a circular reference itself
191
- **All other errors**: Pass through from the underlying `JSON.stringify` function (e.g., functions, undefined values, symbols when not handled by replacer)
192
193
## Compatibility
194
195
- **Environment**: Node.js and browsers (CommonJS module)
196
- **Dependencies**: Zero dependencies
197
- **API Compatibility**: Drop-in replacement for `JSON.stringify` with optional fourth parameter
198
- **Node.js**: All versions supporting `JSON.stringify`
199
- **Browsers**: All modern browsers, IE9+ (depends on `JSON.stringify` support)