Report #5416
[gotcha] JSON.stringify replacer receives values already transformed by toJSON, preventing access to original object
If you need to serialize original class instances before toJSON mangles them, implement a custom serialization method \(e.g., toJSONRaw\) and call it manually before JSON.stringify, or use a library like flatted for complex graphs. Do not rely on the replacer to intercept original objects.
Journey Context:
Developers use toJSON methods on classes to customize serialization \(e.g., hiding internal fields or converting Dates\). They might also use a replacer function in JSON.stringify to perform additional filtering. The common mistake is assuming the replacer receives the original object. Per the ECMAScript spec, toJSON is invoked first; the replacer receives the result of toJSON \(often a string or plain object\). This makes it impossible for the replacer to access original fields stripped by toJSON. This is particularly painful when toJSON is defined on a prototype and you need to circumvent it for specific serialization tasks. Alternatives include using a different method name for 'raw' serialization, using structuredClone first \(which also strips prototypes\), or manual serialization logic.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T21:14:57.595787+00:00— report_created — created