How a Misused JSON.stringify Almost Cost a Bonus – Lessons Learned
A real‑world story shows how a developer’s incorrect use of JSON.stringify caused a missing form field, broke a page, and nearly cost a year‑end bonus, followed by a detailed explanation of JSON.stringify’s quirks and a robust fix to prevent the issue.
My friend, nicknamed "Fat Head", almost lost his year‑end bonus because a bug caused by an incorrect use of JSON.stringify broke a page that users could not submit.
The product manager complained that the form was unusable, the tester wondered why it worked before, and the backend developer pointed out that the request lacked the value field, which JSON.stringify had omitted when its value was undefined.
Because optional fields were undefined, the resulting JSON lacked the value property, so the server could not parse the data and threw an error. The quick fix was to replace undefined with an empty string before stringifying:
let newSignInfo = signInfo.map(it => {
const value = typeof it.value === 'undefined' ? '' : it.value;
return { ...it, value };
});
console.log(JSON.stringify(newSignInfo));
// '[{"fieldId":539,"value":""},{"fieldId":540,"value":""},{"fieldId":546,"value":""}]'After fixing the bug, the team reflected on why it happened: a small optimization request led to a code change, but the developer was unfamiliar with JSON.stringify and did not test thoroughly.
To avoid similar problems, the article reviews the key characteristics of JSON.stringify:
If the target object has a toJSON() method, it defines the data to be serialized.
Boolean, Number, and String objects are converted to their primitive values. undefined, functions, and symbols are omitted in objects and become null in arrays.
All symbol‑keyed properties are ignored. Date objects implement toJSON and are serialized as ISO strings.
Infinity, NaN, and null are serialized as null.
Other objects (including Map, Set, WeakMap, WeakSet) serialize only their enumerable properties.
Circular references cause a TypeError (“Converting circular structure to JSON”).
Attempting to stringify a BigInt throws a TypeError.
Finally, a simple custom implementation of JSON.stringify is provided, demonstrating how to detect circular references, handle toJSON, process arrays and objects, and apply the same rules listed above.
Understanding these rules helps developers avoid subtle bugs caused by missing or altered fields during JSON serialization.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
