Sub topic 3
The JSON Round-Trip and What It Breaks
Before structuredClone was built in, the usual way to get a deep copy in JavaScript was one line: JSON.parse(JSON.stringify(value)). You will still see it in older codebases, Stack Overflow answers and utility files. It works for some data. For other data it quietly changes or drops values, and that leads to bugs that are hard to trace.
This chapter assumes you know JavaScript objects, arrays and primitive types, spread syntax, the basics of Date, Map and Set, and try/catch. It also assumes you have read the previous chapter on shallow copies, so you know why nested data is shared after a spread.
How the Round-Trip Works
The trick has two steps. JSON.stringify walks the value and writes it out as a JSON text string. JSON.parse reads that string and builds brand new objects and arrays from it. Because the result is rebuilt from text, it cannot share any references with the original. That is why it acts as a deep copy.
The catch is the middle step. JSON is a small text format with six kinds of value: objects, arrays, strings, numbers, booleans and null. Anything that does not fit one of those has to be converted, dropped or rejected on the way in. It cannot come back on the way out.
What Survives Intact
Data that is already JSON-shaped comes through unchanged:
- Plain objects with string keys
- Arrays without holes
- Strings, booleans and
null - Finite numbers other than
-0
const settings = { theme: 'dark', fontSize: 14, panels: [{ id: 1, open: true }], owner: null };
const copy = JSON.parse(JSON.stringify(settings));
copy.panels[0].open = false;
console.log(settings.panels[0].open); // true
console.log(copy);
// { theme: 'dark', fontSize: 14, panels: [ { id: 1, open: false } ], owner: null }If your data comes from a JSON API and you never add anything to it, the round-trip copies it correctly. The trouble starts as soon as the data holds anything else.
What It Changes or Drops
Here is the example from the Topic Spine. It shows four kinds of loss in one object:
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: {} }Each change has its own cause:
Datehas atoJSONmethod that returns an ISO string.JSON.parsehas no way to know the string used to be a date, so it stays a string. Code that later callscopy.when.getTime()throws aTypeError.undefinedis not a JSON value. When a property holds it,JSON.stringifyleaves out the whole property, so themissingkey is gone.'missing' in copyisfalse.NaN,Infinityand-Infinityhave no JSON form and becomenull.SetandMapkeep their contents in internal slots, not in enumerable properties.JSON.stringifyonly sees own enumerable string-keyed properties, finds none, and writes{}. The data is gone without any error.
Arrays Follow Different Rules
Inside an array, a value cannot simply be left out, because that would shift every later index. So values that would be dropped in an object become null instead:
const list = [1, undefined, () => {}, Symbol('x'), NaN, Infinity, -0];
console.log(JSON.stringify(list)); // '[1,null,null,null,null,null,0]'
const sparse = [1, , 3];
console.log(JSON.parse(JSON.stringify(sparse))); // [ 1, null, 3 ]The last value in list also shows a quieter change: -0 is written as 0. Object.is(copy, -0) is false after the trip. This matters in code that uses the sign of zero, such as some maths and graphics code.
Full Reference Table
| Original value | In an object property | In an array | Notes |
|---|---|---|---|
| `Date` | ISO string | ISO string | Done by `Date.prototype.toJSON` |
| `undefined` | Property removed | `null` | Top-level `undefined` makes `stringify` return `undefined` |
| Function | Property removed | `null` | Methods disappear |
| Symbol value | Property removed | `null` | Symbol keys are always ignored |
| `NaN`, `Infinity`, `-Infinity` | `null` | `null` | |
| `-0` | `0` | `0` | |
| `Map`, `Set` | `{}` | `{}` | Contents lost |
| `RegExp` | `{}` | `{}` | Pattern and flags lost |
| `Error` | `{}` | `{}` | `message` and `stack` are not enumerable |
| Typed array | `{"0":1,"1":2}` | same | Becomes a plain object with index keys |
| Class instance | Plain object | Plain object | Prototype, methods and prototype getters lost |
| Array hole | n/a | `null` | |
| `BigInt` | `TypeError` | `TypeError` | |
| Circular reference | `TypeError` | `TypeError` |
Class Instances Lose Their Identity
A class instance comes back as a plain object that holds only its own enumerable data properties:
class Point {
constructor(x, y) { this.x = x; this.y = y; }
get length() { return Math.hypot(this.x, this.y); }
}
const copy = JSON.parse(JSON.stringify(new Point(3, 4)));
console.log(copy instanceof Point); // false
console.log(copy.length); // undefined
console.log(copy); // { x: 3, y: 4 }The length getter lives on Point.prototype, not on the instance, so it is never serialized. Non-enumerable own properties are skipped too, which is why an Error turns into {}.
Shared References Get Duplicated
If two properties point to the same object, the copy holds 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); // 1The original had one object reachable by two paths. The copy has two objects. If your code depends on updates through one path being visible through the other, the copy behaves differently from the original. A later chapter shows how structuredClone keeps this sharing.
What It Refuses: Thrown Errors
Some inputs make JSON.stringify throw. Throwing is better than silent loss, but it still breaks code that assumed the copy always works.
const node = { name: 'root' };
node.self = node;
try {
JSON.stringify(node);
} catch (err) {
console.log(err.name); // 'TypeError' (circular structure)
}
try {
JSON.stringify({ big: 10n });
} catch (err) {
console.log(err.name); // 'TypeError' (BigInt cannot be serialized)
}The error message text depends on the engine. V8 (Chrome and Node.js) says "Converting circular structure to JSON" and "Do not know how to serialize a BigInt", while Firefox uses different wording. Check err.name or instanceof TypeError rather than matching the message.
There is one more edge case at the top level. JSON.stringify(undefined) and JSON.stringify(() => {}) return undefined instead of a string. JSON.parse(undefined) then converts its argument to the string "undefined" and throws a SyntaxError:
function jsonCopy(value) {
return JSON.parse(JSON.stringify(value));
}
try {
jsonCopy(undefined);
} catch (err) {
console.log(err.name); // 'SyntaxError'
}A generic jsonCopy helper will therefore fail on an optional value that happens to be missing.
toJSON Can Change What Gets Copied
Before writing any object, JSON.stringify checks for a toJSON method and serializes whatever it returns. Date is the built-in example, but any object or library type can define one:
const account = {
id: 7,
secret: 'hunter2',
toJSON() { return { id: this.id }; }
};
console.log(JSON.parse(JSON.stringify(account))); // { id: 7 }This is useful when you are sending data over the network. It is surprising when you only wanted a copy, because the copy now follows rules written for serialization. Types from libraries such as decimal or date packages often define toJSON, so the round-trip turns them into strings.
Patching It with a Replacer and Reviver
Both JSON functions take an optional callback. A replacer passed to JSON.stringify can rewrite values before they are written, and a reviver passed to JSON.parse can rebuild them afterwards. With both, you can carry some types through by tagging them:
function replacer(key, value) {
const raw = this[key]; // the value before toJSON ran
if (raw instanceof Date) return { __type: 'Date', iso: raw.toISOString() };
if (raw instanceof Map) return { __type: 'Map', entries: [...raw] };
if (raw instanceof Set) return { __type: 'Set', values: [...raw] };
return value;
}
function reviver(key, value) {
if (value && typeof value === 'object') {
if (value.__type === 'Date') return new Date(value.iso);
if (value.__type === 'Map') return new Map(value.entries);
if (value.__type === 'Set') return new Set(value.values);
}
return value;
}
const original = {
when: new Date(0),
tags: new Set(['a']),
meta: new Map([['k', { at: new Date(1000) }]])
};
const copy = JSON.parse(JSON.stringify(original, replacer), reviver);
console.log(copy.when instanceof Date); // true
console.log(copy.tags.has('a')); // true
console.log(copy.meta.get('k').at.getTime()); // 1000The replacer reads this[key] and does not use value. toJSON runs before the replacer, so for a Date the value argument is already a string. this is the object that holds the property, so this[key] is still the real Date.
The reviver works from the inside out. Nested values are revived before their parents, so the Date inside the Map entry already exists when the Map is built.
This approach has limits:
- You must add a branch for every type you care about, and any type you forget is still lost.
- A real data object that happens to have a
__typefield will be mistaken for a tag. - Circular references and
BigIntstill throw, and shared references are still duplicated. - Class instances still need custom code for each class.
At this point you are writing a small custom cloner on top of a text format. It is worth knowing how to do it, mainly because it shows how much work the next chapter's built-in tool saves.
When the Round-Trip Is Still Reasonable
The JSON round-trip is a fair choice when both of these are true:
- The data is JSON-shaped by construction. For example, it was just parsed from an API response or a config file and has not been changed since.
- You actually want JSON rules applied. For example, you are building a snapshot that will be saved or sent as JSON anyway, so dropping functions and turning dates into strings is the behaviour you need.
In those cases the round-trip also checks that the data really is serializable. Outside those cases, treat JSON.parse(JSON.stringify(x)) as a serialization step that happens to return an object, not as a general deep copy.
Exercise
What does this log, and why? const input = { a: [undefined, 1], b: undefined, c: new Map([['x', 1]]), d: -0 }; console.log(JSON.stringify(input));
Show answer
It logs '{"a":[null,1],"c":{},"d":0}'. Inside the array, undefined becomes null so the indexes stay in place. The property b holds undefined, so it is left out completely. The Map has no own enumerable properties, so it becomes {}. -0 is written as 0.
Exercise
A teammate's replacer checks "if (value instanceof Date)" and the Date branch never runs. Why, and how do you fix it?
Show answer
JSON.stringify calls Date.prototype.toJSON before it calls the replacer, so the value argument is already an ISO string, not a Date. Inside a normal function replacer, read the original with this[key], which still holds the Date, and test that instead. An arrow function will not work here because it does not receive the holder object as this.
Exercise
You run jsonCopy(state) on an object where state.current and state.history[0] point to the same object. After the copy, the code updates copy.current.title. Does copy.history[0].title change? What changes if state.history[0].parent = state is added?
Show answer
No. The round-trip writes the shared object out twice and parses it into two separate objects, so changing one does not affect the other. If you add a circular reference back to state, JSON.stringify throws a TypeError and no copy is made.