Sub topic 3
The JSON Round-Trip and What It Breaks
This chapter assumes you know JavaScript objects, arrays and primitive types, and the basic use of Date, Map and Set. It also assumes you can run code in a browser console or Node.js and that you have seen try/catch. The previous chapter showed that a shallow copy still shares its nested objects with the original. Before structuredClone existed, the usual fix was a JSON round-trip.
How the Round-Trip Works
JSON.stringify turns a value into a string. JSON.parse builds brand-new objects and arrays from that string. Nothing in the result points back to the original, so you get a deep copy.
const original = { user: { name: 'Ada' }, tags: ['a'] };
const copy = JSON.parse(JSON.stringify(original));
copy.user.name = 'Grace';
copy.tags.push('b');
console.log(original.user.name); // 'Ada'
console.log(original.tags); // ['a']For plain data made only of strings, finite numbers, booleans, null, plain objects and arrays, this works well. The trouble is that the copy contains only what JSON can represent. Anything else gets converted, dropped or rejected along the way.
Silent Type Changes and Data Loss
Most of the damage happens without any error:
const data = { when: new Date(0), missing: undefined, ratio: NaN, ids: new Set([1, 2]) };
const copy = JSON.parse(JSON.stringify(data));
console.log(copy);
// { when: '1970-01-01T00:00:00.000Z', ratio: null, ids: {} }Here is what happened to each property:
| Original value | After the round-trip | Why |
|---|---|---|
| `Date` | ISO string | `Date.prototype.toJSON` returns a string, and `JSON.parse` never turns it back into a `Date` |
| `undefined` property | Removed | JSON has no `undefined` |
| `NaN`, `Infinity` | `null` | JSON numbers must be finite |
| `Set`, `Map` | `{}` | They have no own enumerable properties to serialize |
| `RegExp` | `{}` | Same reason as `Set` and `Map` |
| Function or symbol value | Removed (`null` inside arrays) | JSON cannot represent them |
| Symbol-keyed property | Removed | Only string keys are serialized |
| Class instance | Plain object | The prototype is not recorded |
Arrays act differently from objects here. JSON.stringify([undefined, () => {}]) produces "[null,null]", because removing entries would shift the indexes.
Values That Throw
Two kinds of input make JSON.stringify throw a TypeError instead of converting the value: circular references and BigInt values.
const node = { name: 'root' };
node.self = node;
try {
JSON.stringify(node);
} catch (err) {
console.log(err.name); // 'TypeError' (message mentions a circular structure)
}
try {
JSON.stringify({ big: 10n });
} catch (err) {
console.log(err.name); // 'TypeError' (BigInt cannot be serialized)
}Shared References Get Duplicated
JSON is a tree format, so it has no way to say "this is the same object as before." If two properties point to one object, the copy gets two separate objects:
const shared = { id: 1 };
const pair = { a: shared, b: shared };
const copy = JSON.parse(JSON.stringify(pair));
console.log(copy.a === copy.b); // false
copy.a.id = 2;
console.log(copy.b.id); // 1If your code depends on those two properties staying linked, the copy behaves differently from the original.
When It Is Still Acceptable
The JSON round-trip is fine when you know the data is already JSON-shaped, for example a parsed API response or a config file. It is also fine when you actually want JSON output, such as for storage or for sending over the network. For anything that holds dates, collections, undefined or linked objects, you need a tool that understands those types. The next chapter introduces that tool.
Exercise
What does JSON.parse(JSON.stringify({ a: [1, undefined, NaN], b: undefined, c: new Map([['x', 1]]) })) return?
Show answer
{ a: [1, null, null], c: {} }. Inside the array, undefined becomes null so the indexes stay the same, and NaN becomes null. The property b is removed because its value is undefined. The Map becomes an empty object because it has no own enumerable properties.
Exercise
A copied object has a createdAt property, and calling copy.createdAt.getFullYear() throws "getFullYear is not a function". The original works. What most likely caused this?
Show answer
The object was copied with a JSON round-trip. JSON.stringify turned the Date into an ISO string, and JSON.parse left it as a string, so it no longer has Date methods.