Skip to content
How Misusing JSON.stringify Almost Cost My Friend His Year‑End Bonus

How Misusing JSON.stringify Almost Cost My Friend His Year‑End Bonus

A real‑world story shows how an overlooked undefined value in a JSON payload caused a front‑end bug that nearly cost a developer his year‑end bonus, and explains the quirks of JSON.stringify together with practical fixes and a custom implementation.

Top Architect
Top Architect
Top Architect

My friend "胖头" (nickname) took over a module after a colleague left, and a bug appeared when the page submitted a form because the JSON payload omitted the value field.

The issue stemmed from JSON.stringify silently dropping properties whose values are undefined, turning them into missing fields that the server could not parse, leading to the failure.

JSON.stringify follows several rules: objects with a toJSON() method define their own serialization, primitive wrappers are converted to primitives, undefined, functions and symbols are omitted in objects (or become null in arrays), Symbol‑keyed properties are ignored, Dates are serialized as ISO strings, and circular references throw a TypeError.

To keep the value field, we can preprocess the data, replacing undefined with an empty string before calling JSON.stringify:

let newSignInfo = signInfo.map(it => {
  const value = typeof it.value === 'undefined' ? '' : it.value;
  return { ...it, value };
});
console.log(JSON.stringify(newSignInfo)); // '[{"fieldId":539,"value":""},...]'

Beyond the fix, I also wrote a simple custom jsonstringify function that mimics the native behavior, handling cyclic references, BigInt errors, and the various type conversions.

const jsonstringify = (data) => {
  // detect cycles
  const isCyclic = (obj) => { /* ... */ };
  if (isCyclic(data)) throw new TypeError('Converting circular structure to JSON');
  if (typeof data === 'bigint') throw new TypeError('Do not know how to serialize a BigInt');
  // handle primitives, arrays, objects, toJSON, etc.
  // (implementation omitted for brevity)
  return result;
};

The story ends with a reminder: understand JSON.stringify’s edge cases, test small changes thoroughly, and you can avoid costly bugs that threaten bonuses or even jobs.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendJavaScriptSerializationJSONbugcodestringify
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.