Introduction
Si tu es développeur, il y a de fortes chances que tu aies déjà utilisé JSON pour échanger des données entre client et serveur. Sa simplicité et sa compatibilité avec JavaScript en font un choix évident. Mais attention, ton JSON pourrait te mentir ! Dans cet article, on va explorer comment la sérialisation et la désérialisation avec JSON peuvent mener à des surprises inattendues.
JSON : Un Outil Essentiel mais Limité
JSON (JavaScript Object Notation) a été popularisé au début des années 2000 comme une alternative légère à XML. Sa simplicité réside dans sa capacité à représenter facilement des objets JavaScript sous forme de texte. Cependant, cette simplicité a un coût : JSON ne peut pas représenter tous les types de données JavaScript.
Prenons un exemple concret : ``javascript const payload = { id: 9007199254740993 }; console.log(JSON.stringify(payload)); // {"id":9007199254740992} ``
Ici, l'ID se termine par 3, mais après la sérialisation, il se termine par 2. Pourquoi ? Parce que JSON utilise le type number de JavaScript, qui est basé sur le format IEEE 754 double précision, et a donc ses limites.
Les Surprises de la Sérialisation
La sérialisation JSON peut transformer tes données de manière inattendue. Voici quelques exemples :
- Nombres : Les grands entiers ne sont pas correctement représentés.
- Types spéciaux :
undefined,NaNne sont pas supportés. - Objets Date : Convertis en chaînes de caractères ISO.
``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 } ``
Comment Rester Maître de Tes Données
Pour éviter ces pièges, voici quelques stratégies :
- Utiliser des bibliothèques tierces : Des outils comme
BigIntpeuvent aider à gérer de grands nombres. - Customiser la sérialisation : Implémente des méthodes
toJSONpour contrôler la sortie JSON. - Valider les données : Avant et après la sérialisation, assure-toi que les données sont conformes à tes attentes.
Conclusion
JSON est un format puissant mais avec des limitations qu'il faut comprendre pour éviter des erreurs subtiles mais potentiellement graves. En adoptant de bonnes pratiques, tu peux t'assurer que tes données sont correctement transmises et interprétées. Discutons de ton projet en 15 minutes.
Sources et Ressources Complémentaires
- [RFC 8259](https://tools.ietf.org/html/rfc8259)
- [Bibliothèques JSON avancées](https://json.org)
---
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)