| LocalStorage-and-SessionStorage | Event Bubbling & Delegation | |
JSON Handling in JavaScript |
JSON (JavaScript Object Notation) is a lightweight data format used for storing and exchanging data. JavaScript provides two built-in methods for working with JSON:
JSON.stringify() – Converts a JavaScript object into a JSON string.JSON.parse() – Converts a JSON string back into a JavaScript object.This method is used to serialize a JavaScript object into a JSON-formatted string.
const user = {
name: "Alice",
age: 25,
isAdmin: false
};
const jsonString = JSON.stringify(user);
console.log(jsonString);
// Output: {"name":"Alice","age":25,"isAdmin":false}
This method is used to deserialize a JSON string back into a JavaScript object.
const jsonString = '{"name":"Alice","age":25,"isAdmin":false}';
const userObject = JSON.parse(jsonString);
console.log(userObject.name); // Output: Alice
The JavaScript JSON.parse() and JSON.stringify() methods are used to convert data between JavaScript objects and the JSON (JavaScript Object Notation) format. These built-in methods are crucial for web development, as JSON is the standard for exchanging data between web pages and servers.
The JSON.parse() method converts a JSON string into a native JavaScript object or value. This is necessary when receiving JSON data from a web server or retrieving it from local storage, since network data and storage are string-based.
JSON.parse(text, reviver)
const jsonString = '{"name": "John", "age": 30}';
try {
const userObject = JSON.parse(jsonString);
console.log(userObject.name); // Output: John
console.log(typeof userObject); // Output: object
} catch (error) {
console.error("Failed to parse JSON:", error.message);
}
The JSON.stringify() method converts a JavaScript object or value into a JSON string. This is essential for sending JavaScript data to a server or storing it in client-side storage.
JSON.stringify(value, replacer, space)
const userObject = {
name: "Alice",
age: 28,
isStudent: true,
};
const jsonString = JSON.stringify(userObject, null, 2); // Indent with 2 spaces
console.log(jsonString);
/*
Output:
{
"name": "Alice",
"age": 28,
"isStudent": true
}
*/
| Aspect | Advantages |
|---|---|
| Simple and lightweight | The JSON API is built-in, easy to use, and highly optimized for performance. |
| Universal data format | JSON is a language-independent standard, allowing seamless data exchange between JavaScript and web servers written in any language. |
| Readability | The JSON text format is human-readable, which aids in debugging and inspection. |
| Aspect | Disadvantages and Limitations |
|---|---|
| Data type limitations | JSON.stringify() does not handle all JavaScript data types. Functions, undefined, Symbol values, and circular references are ignored or cause errors. Date objects are converted to strings. |
| Strict syntax | JSON.parse() is very strict and will throw a SyntaxError for malformed JSON, such as trailing commas or unquoted keys. |
| No security features | JSON itself offers no security, and JSON payloads can be intercepted and tampered with during transmission if not encrypted with HTTPS. |
JSON.stringify() to save objects and arrays to localStorage or sessionStorage, and JSON.parse() to retrieve them.JSON.parse(JSON.stringify(obj)) for a simple (but limited) deep copy of plain data.JSON.parse(JSON.stringify()) to deep clone objects that contain functions, Dates, or other non-serializable types, as these will be lost.JSON.parse() calls in a try...catch block, especially when dealing with data from external sources, to handle potential parsing errors gracefully.structuredClone() method or a robust library like Lodash's cloneDeep().JSON.parse() data from an untrusted source without first validating and sanitizing it to protect against malicious JSON injection attacks.space argument in JSON.stringify() to pretty-print your JSON for easier readability during development.localStorage or sessionStorageundefined, and circular references are not supported in JSON.JSON.parse() in a try...catch block to handle errors safely.JSON.stringify() before storing objects in browser storage.JSON.parse() when retrieving and using stored JSON data.JSON.stringify(obj, null, 2)const settings = {
theme: "dark",
notifications: true
};
// Store in localStorage
localStorage.setItem("settings", JSON.stringify(settings));
// Retrieve from localStorage
const savedSettings = JSON.parse(localStorage.getItem("settings"));
console.log(savedSettings.theme); // Output: dark
| LocalStorage-and-SessionStorage | Event Bubbling & Delegation | |