Master JSON in JavaScript: From Serialization Basics to Advanced Tricks
This article explains what JSON is, why it’s ideal for data exchange, contrasts it with JavaScript objects, and dives deep into JSON.stringify, JSON.parse, and toJSON, illustrating each concept with clear code examples and practical tips for developers.
What Is JSON?
JSON (JavaScript Object Notation) is a lightweight, text‑based data‑exchange format that is easy for humans to read and write and easy for machines to parse. It is language‑independent, making it ideal for transmitting structured data between client‑side JavaScript and server‑side applications.
JSON vs. JavaScript Objects
Although JSON’s syntax derives from JavaScript object literals, the two are fundamentally different: JSON is a strict string format, while a JavaScript object is an in‑memory data structure. JSON requires double‑quoted keys and values, does not allow functions, undefined, or symbols, and enforces a well‑defined order for arrays.
Serializing JavaScript Data – JSON.stringify
The signature is JSON.stringify(value[, replacer[, space]]). It converts a JavaScript value to a JSON string, applying several “smart” rules:
Keys without double quotes are automatically quoted.
Single‑quoted strings become double‑quoted.
Trailing commas are removed.
Non‑enumerable properties, functions, undefined, Symbol, NaN, Infinity become null in arrays or are omitted in objects.
var friend = {
firstName: "Good",
lastName: "Man",
address: undefined,
phone: ["1234567", undefined],
fullName: function(){ return this.firstName + " " + this.lastName; }
};
JSON.stringify(friend); // "{\"firstName\":\"Good\",\"lastName\":\"Man\",\"phone\":[\"1234567\",null]}"Using a replacer function
var friendAfter = JSON.stringify(friend, function(key, value){
if(key === "phone") return "(000)" + value;
if(typeof value === "number") return value + 10;
return value;
});
console.log(friendAfter); // {"firstName":"Good","lastName":"Man","phone":"(000)1234567","age":28}Using a replacer array
var friendAfter = JSON.stringify(friend, ["firstName","address","phone"]);
console.log(friendAfter); // {"firstName":"Good","phone":"1234567"}Pretty‑printing with the third argument
var friendAfter = JSON.stringify(friend, null, 4);
console.log(friendAfter);
/*
{
"firstName": "Good",
"lastName": "Man",
"phone": {
"home": "1234567",
"work": "7654321"
}
}
*/Parsing JSON – JSON.parse
The signature is JSON.parse(text[, reviver]). It throws an error if the input string is not valid JSON. An optional reviver function can transform values during parsing.
JSON.parse(friendAfter, function(k, v){
console.log(k);
console.log(v);
console.log("----");
});
/* Output shows a depth‑first traversal of the parsed object */Customizing Serialization – toJSON
If an object defines a toJSON method, JSON.stringify uses the value returned by that method instead of the original object.
var info = {
msg: "I Love You",
toJSON: function(){
var replaceMsg = {};
replaceMsg["msg"] = "Go Die";
return replaceMsg;
}
};
JSON.stringify(info); // "{\"msg\":\"Go Die\"}"Special Cases
In objects, undefined, functions, and symbols are omitted.
In arrays, those values become null. NaN, Infinity, and -Infinity become null.
Conclusion
JSON is a concise, language‑agnostic format that simplifies data exchange between front‑end JavaScript and back‑end services. Understanding the nuances of JSON.stringify, JSON.parse, and toJSON helps developers write robust, interoperable code while keeping payloads as small as possible.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
