Object Serialization With JSON
Level: Beginner
Serialization is the process of converting an object in memory into a static format such as a string or binary blob. In JavaScript, the string format JSON is the standard for object serialization. JSON, afterall, stands for JavaScript Object Notation, and is based on the source code format used inside JavaScript for objects, so it’s only fitting.
To serialize an object in JavaScript, you can use the JSON
object. It provides methods for both converting an object into JSON as well as converting a JSON string back to an object.
let obj = { prop: 'value' };
let str = JSON.stringify(obj);
console.log(str); // "{"prop":"value"}"
console.log(typeof str); // string
let objAgain = JSON.parse(str);
console.log(objAgain); // { prop: 'value' }
console.log(typeof objAgain); // object
Having a JSON representation of your object makes it easy to do things like save it to disk (maybe through localStorage
) or send it off somewhere else like a web server for processing or storing.
But JSON isn’t without its limitations. It only supports a subset of values which are possible in JavaScript. These include: ordinary objects, arrays, numbers, strings, booleans, and null. Other values such as functions and undefined, when stored in object properties, are ignored completely during the serialization process (though in arrays, undefined values are converted to null). Numbers are also limited in that special number values like NaN
and Infinity
are not fully supported and are instead converted to null.
let obj = {
prop: undefined,
getProp () {
return this.prop;
},
count: Infinity
};
let serializedObj = JSON.stringify(obj);
console.log(serializedObj); // "{ "count": null }"
let arr = [1, undefined, 3];
let serializedArr = JSON.stringify(arr);
console.log(serializedArr); // "[1, null, 3]"
Despite these limitations, JSON is still used heavily throughout the JavaScript ecosystem and can be a useful tool when it comes to managing your data.
More info: