Introduction
If you're a developer, chances are you've used JSON to exchange data between client and server. Its simplicity and compatibility with JavaScript make it an obvious choice. But beware, your JSON might be lying to you! In this article, we will explore how serialization and deserialization with JSON can lead to unexpected surprises.
JSON: An Essential Yet Limited Tool
JSON (JavaScript Object Notation) gained popularity in the early 2000s as a lightweight alternative to XML. Its simplicity lies in its ability to easily represent JavaScript objects as text. However, this simplicity comes at a cost: JSON cannot represent all JavaScript data types.
Let's take a concrete example: ``javascript const payload = { id: 9007199254740993 }; console.log(JSON.stringify(payload)); // {"id":9007199254740992} ``
Here, the ID ends in 3, but after serialization, it ends in 2. Why? Because JSON uses JavaScript's number type, which is based on IEEE 754 double precision format and thus has its limits.
Serialization Surprises
JSON serialization can transform your data in unexpected ways. Here are some examples:
- Numbers: Large integers are not correctly represented.
- Special Types:
undefined,NaNare not supported. - Date Objects: Converted to ISO string representations.
``javascript const original = { id: 9007199254740993, missing: undefined, createdAt: new Date('2026-07-21T12:00:00Z'), score: NaN }; const copy = JSON.parse(JSON.stringify(original)); console.log(copy); // { id: 9007199254740992, createdAt: "2026-07-21T12:00:00.000Z", score: null } ``
How to Maintain Control Over Your Data
To avoid these pitfalls, here are some strategies:
- Use Third-Party Libraries: Tools like
BigIntcan help manage large numbers. - Customize Serialization: Implement
toJSONmethods to control JSON output. - Validate Data: Before and after serialization, ensure that data meets your expectations.
Conclusion
JSON is a powerful format but with limitations that must be understood to avoid subtle yet potentially serious errors. By adopting best practices, you can ensure that your data is correctly transmitted and interpreted. Let's discuss your project in 15 minutes.
Sources and Further Reading
- [RFC 8259](https://tools.ietf.org/html/rfc8259)
- [Advanced JSON Libraries](https://json.org)