Serialization and Deserialization in JS


What is Serialization?
Serialization is the process of converting a value into a string format so it can be stored or transmitted. Let’s say we want to build a teleportation system. First, we take an array human
, which will have all the properties that define a human:
const human = ["nose", "ear", "eyes", "legs", "arms", "body"];
We can serialize the human
array using JSON.stringify()
:
const myJson = JSON.stringify(human);
console.log(myJson);
Output:
["nose", "ear", "eyes", "legs", "arms", "body"]
The compiler formats the output, so we don’t see single quotes around the JSON string.
What is Deserialization?
Deserialization means converting a string value back to its original value. We can now convert our human
array, which is in string format, back to its original form using deserialization:
const deserialized = JSON.parse(myJson);
console.log(deserialized);
Output:
["nose", "ear", "eyes", "legs", "arms", "body"]
What we did here is convert the value back to its original form, essentially "teleporting" a human back. However, during serialization and deserialization, we may encounter issues such as data corruption, data loss, or format incompatibility. To handle these issues, we can take specific preventive measures.
Here is the structure what we did
How to Prevent Data Loss
To prevent data loss, we can use a replacer function during serialization to include or exclude specific values and a reviver function during deserialization to restore missing or transformed data.
For example, if an element in the array is undefined
, JSON.stringify()
will remove it. We can replace it with a placeholder value like "missing":
const human = ["nose", "ear", undefined, "legs", "arms", "body"];
const serialized = JSON.stringify(human, (key, value) =>
value === undefined ? "missing" : value
);
console.log(serialized);
Output:
["nose", "ear", "missing", "legs", "arms", "body"]
This ensures that missing values don’t cause unexpected issues.
How to Prevent Format Incompatibility
Different systems might expect different JSON structures. To maintain compatibility:
- Use versioning in JSON:
const human = { version: 1, bodyParts: ["nose", "ear", "eyes", "legs"] };
const serialized = JSON.stringify(human);
console.log(serialized);
//output {"version":1,"bodyParts":["nose","ear","eyes","legs"]}
- Check data structure before deserialization:
const jsonString = '{"type":"bodyParts","parts":["nose","ear","eyes"]}';
try {
const parsed = JSON.parse(jsonString);
if (!parsed.parts || !Array.isArray(parsed.parts)) {
throw new Error("Invalid format");
}
console.log(parsed.parts);
} catch (error) {
console.error("Data format issue:", error.message);
}
//output ["nose", "ear", "eyes"]
This prevents errors when the expected structure changes.
How to Handle Data Corruption
Data corruption can happen due to network issues, manual edits, or storage problems. To handle this:
- Validate JSON before parsing:
const isValidJson = (str) => {
try {
JSON.parse(str);
return true;
} catch {
return false;
}
};
console.log(isValidJson('["nose","ear","eyes"]')); // true
console.log(isValidJson('{nose: "ear"}')); // false (corrupt JSON)
- Use try...catch to prevent crashes:
const corruptedJson = '["nose","ear",legs,"arms"]'; // Incorrect JSON format
try {
const parsed = JSON.parse(corruptedJson);
console.log(parsed);
} catch (error) {
console.error("Corrupt data detected:", error.message);
}
//output Corrupt data detected: Unexpected token l in JSON at position 13
- Use backups or checksums:
Store unmodified copies of JSON.
Implement hashing to verify data integrity before parsing.
Conslusion
Serialization and deserialization are essential for data storage and transfer. However, to ensure data integrity and compatibility, always:
Handle missing values with replacers and revivers.
Use versioning and validate JSON structures.
Implement error handling for corrupted data.
Subscribe to my newsletter
Read articles from rohit directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
