JSON.parse & JSON.stringify
debt(d5/e3/b3/t7)
Closest to 'specialist tool catches it' (d5). ESLint can detect missing try/catch around JSON.parse and obvious circular reference patterns, but silent data loss from undefined values or Date serialisation requires runtime testing or code review to catch reliably.
Closest to 'simple parameterised fix' (e3). The quick_fix is wrapping JSON.parse in try/catch (one-line or simple block addition). Fixing data loss from Date objects or undefined values requires refactoring the parsing/stringifying logic within one component, not cross-cutting changes.
Closest to 'localised tax' (b3). JSON.parse and JSON.stringify are used throughout web/CLI codebases, but the burden is localised to each call site. Developers must remember the edge cases at each usage point, but no single architectural choice poisons the whole system. The tax is repeated, not load-bearing.
Closest to 'serious trap' (t7). The misconception field directly states the trap: JSON.parse appears safe (it's a built-in), but PHP integration breaks the assumption — PHP error pages return HTML, not JSON, causing silent SyntaxError. Additionally, the common_mistakes list reveals multiple gotchas (Date loss, undefined silently dropped, circular references crash) that contradict intuitive expectations of a 'serialisation round-trip'. Developers new to JSON.parse often assume it's always safe or that it preserves all JavaScript types.
Also Known As
TL;DR
Explanation
JSON.stringify(value, replacer, space) — replacer filters/transforms keys, space pretty-prints. JSON.parse(text, reviver) — reviver transforms parsed values (e.g. date string to Date object). Both throw on invalid input. Circular references throw in stringify. undefined, functions, and Symbol values are omitted from stringified output. PHP json_decode($str, true) returns associative array; without true returns stdClass — know which you're consuming in JavaScript.
Common Misconception
Why It Matters
Common Mistakes
- Not wrapping JSON.parse in try/catch
- Losing Date objects (serialised as strings, not revived automatically)
- undefined values silently dropped by JSON.stringify
- Circular reference crash in JSON.stringify
Code Examples
// Silent failures:
const data = JSON.parse(serverResponse); // Crashes on HTML error page
const payload = JSON.stringify({ id: 1, fn: () => {} }); // fn silently dropped
// Safe parse with fallback:
let data;
try {
data = JSON.parse(serverResponse);
} catch (e) {
console.error('Non-JSON response:', serverResponse.slice(0, 200));
throw new Error('Server returned unexpected format');
}
// Replacer to control output:
const payload = JSON.stringify(obj, (key, val) =>
typeof val === 'function' ? undefined : val
, 2);