Values disappearing with JSON.stringify? Checking undefined, NaN, and date changes with safe data

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About this article
This article was created using an automated generation workflow utilizing generative AI. We verified the JavaScript JSON conversion specifications against official documentation and confirmed the conversion results using hypothetical data in a JavaScript execution environment. The Node.js test file included in the learning materials and its display in WordPress have not yet been verified.

Verification status: 🧪 Conversion results with hypothetical data have been verified. Node.js material tests and production screens are unverified.

If you encounter an issue where saved settings disappear upon reloading, before suspecting a file write failure, take a look at the exact moment the data was converted to JSON. JavaScript objects and JSON look similar, but they are not the same thing. JSON is a data format that can be passed around as a string, but it cannot represent every value available in JavaScript as-is.

In this article, we will convert a hypothetical order number and numerical values without using actual configuration files or APIs.Even though JSON is successfully generated at a glance, only the meaning of the values changesHowever, this is an important point of observation.

Let's try first: Comparing before and after conversion

No additional packages are required. The learning materials, assuming Node.js 20 or later, have been placed inDaily Code completed version and README. We assume you run node app.mjs in the downloaded material folder. All inputs used here are dummies, and there is no external transmission or modification of actual files.

The materials include app.mjs、test.mjs、README.md, which separates implementation and inspection. There is no need to paste actual business data. The program first displays the converted JSON string and then indicates the differences between the original and reloaded values using boolean values.

The following snippet is the input to be observed.

const input = {
  id: "DUMMY-001",
  optional: undefined,
  score: NaN,
  limit: Infinity,
  at: new Date("2026-01-01T00:00:00.000Z"),
  items: ["A", undefined, "C"]
};
const json = JSON.stringify(input);
const restored = JSON.parse(json);
console.log(json);

The JSON string verified in the JavaScript execution environment had the following form. This is not a formatted explanatory mockup, but the result of converting the values above.

{"id":"DUMMY-001","score":null,"limit":null,"at":"2026-01-01T00:00:00.000Z","items":["A",null,"C"]}

Here is our first finding.optional disappears along with its key. On the other hand, the one located in the middle of the array undefined has changed to null. Even the same undefined, the output differs depending on where it is placed.

Where does it change? Viewing the processing flow in a diagram

The following diagram does not depict a storage failure. The value changes at the boundary of serialization before saving and subsequent deserialization. Tracing from left to right, we can see that lost types and values cannot be restored by JSON.parse alone.

flowchart LR
  A["JavaScriptの値"] --> B["JSON.stringify"]
  B --> C["JSON文字列: 省略・null・文字列"]
  C --> D["JSON.parse"]
  D --> E["別のJavaScript値"]

The right end of the diagram is not an exact copy of the left end. For example, a date Date object is entered into JSON as an ISO-formatted string representing the date and time. Since it remains a string even after being read back, explicit conversion is required before using date methods. However, unconditionally converting any received string into a date causes a different problem. It is important to design a system that predetermines which fields should be treated as dates.

Understanding why values disappear one by one

JSON.stringify omits the property from the output if the property value of the object is undefined. In other words, optional: undefined enters a state where the item "optional" itself does not exist within the JSON. Treating this as having the same meaning as optional: null is dangerous. This is because API update processing may be designed so that "not specified" and "explicitly cleared" have different meanings.

The situation is different for arrays.["A", undefined, "C"] The central element of null remains as

NaN is a special value indicating that a numeric calculation did not result in a valid number.Infinity is a numeric value representing infinity. Since neither can be represented as a normal JSON number, JSON.stringify then becomes null. Even if you check null on the reading side, you cannot distinguish whether the original was NaN, Infinity, or null from the beginning. For monitoring data or aggregated values, it is safer to store the reason for missing data in a separate field.

Date is an object that internally holds a date and time, but it typically becomes a string in JSON. The at this time becomes "2026-01-01T00:00:00.000Z". The trailing Z represents UTC. Converting it to Japan Standard Time also requires handling time zones, and simply displaying the string again does not necessarily match the time representation expected by the user.

Compare by changing only one condition

Change the first score: NaN to score: 0 and run JSON.stringify again. This time, the score in the JSON becomes null instead of 0.Zero is a measured numerical value, while NaN is an uncomputable value, and their business meanings are completely different. For example, ensure you do not confuse whether a sales aggregation had zero entries or could not be calculated due to input anomalies.

Next, if you change optional: undefined to optional: null, the keys of optional will be retained. This demonstrates that even if the visual representation of having "no data" appears the same, the information transmitted to the destination differs. However, which approach should be adopted depends on the API or storage format contract. Uniformly replacing values with null is not always the correct solution.

When comparing, do not modify multiple items simultaneously. By changing only one item at a time and observing the difference, it becomes easier to trace which conversion rule caused the issue. The tutorial function audit is a helper designed to separately evaluate changes in missing properties, special numeric values, dates, and arrays.

Isolating Failures and Boundary Conditions

The examples so far have involved cases where a JSON string is successfully generated. However, not all inputs will succeed. For instance, if you include BigInt using the standard method, TypeError will occur. Objects containing circular references also cannot be serialized to JSON as-is. If an exception occurs, do not automatically assume it is a file or network issue; first inspect the input types and reference structure.

JSON.stringify(undefined) The return value of "undefined" is not the string undefined, but a JavaScript JSON.parse. If you pass this directly to

, it cannot be parsed. This also differs from the behavior where undefined values within an object are omitted. It is important to verify whether the entire input consists of JSON-serializable values.JSON.parseNote that the result of Date does not have an automatic restoration feature for NaN or

How to Differentiate Usage in Production

It is premature to conclude that data is safe just because it has been converted to JSON before logging or API transmission. Enumerate critical fields that cannot afford to be lost—such as order numbers, amounts, deadlines, and reasons for missing data—and verify their value types and ranges before sending. Specifically, for monetary amounts,Number.isFinitespecific rules are required, such as using [placeholder] to accept only finite numbers, or defining an input format for dates to validate their correctness.

On the other hand, there are cases where omitting fields such as [placeholder],undefinedwhich contain temporary information for screen display, is intended. The key is not to avoid JSON conversion itself, but to design a contract regarding which values to retain. If both the sender and receiver understand the same schema, there is no need to later guess "missing values."

This learning material is designed to observe basic JSON data loss through small inputs. It does not provide encryption, sensitive information masking, complete replication, or database transactions. Before adopting it in actual systems, separately verify the target API specifications, handling of abnormal values, potential inclusion of confidential information in logs, and compatibility across multiple versions.

Official Information and Verification Scope

The serialization and deserialization of the dummy inputs used here were compared in a JavaScript execution environment. This does not imply that the instructional test files for Node.js were executed in Node.js, verified on Windows/macOS or browser screens, or displayed on WordPress. Also, please note any discrepancies between the specifications linked in the official documentation and the implementation environment.

Document information

Article title
Values disappearing with JSON.stringify? Checking undefined, NaN, and date changes with safe data
Published
Updated
Source
https://papanda925.com/?p=18639&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL