Home >Web Front-end >JS Tutorial >Mastering JSON Handling in JavaScript: Parsing and Stringifying
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. JavaScript provides built-in methods for parsing JSON strings into objects and converting objects into JSON strings.
The JSON.parse() method is used to convert a JSON string into a JavaScript object.
JSON.parse(text[, reviver]);
A. Simple Parsing
const jsonString = '{"name": "John", "age": 30}'; const parsedData = JSON.parse(jsonString); console.log(parsedData.name); // Output: John console.log(parsedData.age); // Output: 30
B. Using a Reviver Function
The reviver function can be used to customize the parsing process.
const jsonString = '{"name": "John", "birthYear": 1990}'; const parsedData = JSON.parse(jsonString, (key, value) => { if (key === "birthYear") { return 2024 - value; // Convert birth year to age } return value; }); console.log(parsedData.birthYear); // Output: 34
Always wrap JSON.parse() in a try...catch block to handle invalid JSON.
const invalidJson = "{name: 'John', age: 30}"; // Invalid JSON (keys must be in quotes) try { const data = JSON.parse(invalidJson); } catch (error) { console.error("Invalid JSON:", error.message); }
The JSON.stringify() method converts a JavaScript object into a JSON string.
JSON.stringify(value[, replacer[, space]]);
A. Simple Stringifying
const data = { name: "John", age: 30 }; const jsonString = JSON.stringify(data); console.log(jsonString); // Output: {"name":"John","age":30}
B. Using a Replacer Function
The replacer function filters or transforms the object’s properties.
const data = { name: "John", age: 30, password: "secret" }; const jsonString = JSON.stringify(data, (key, value) => { if (key === "password") return undefined; // Exclude passwords return value; }); console.log(jsonString); // Output: {"name":"John","age":30}
C. Adding Indentation
The space parameter formats the output with indentation.
const data = { name: "John", age: 30 }; const jsonString = JSON.stringify(data, null, 2); console.log(jsonString); // Output: // { // "name": "John", // "age": 30 // }
Circular references in objects cause JSON.stringify() to throw an error.
const circularObject = {}; circularObject.self = circularObject; try { JSON.stringify(circularObject); } catch (error) { console.error("Cannot stringify circular object:", error.message); }
Convert a JavaScript object into a JSON string before sending it in an HTTP request.
const data = { name: "John", age: 30 }; fetch("https://example.com/api", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });
Save and retrieve data in JSON format using localStorage.
const data = { name: "John", age: 30 }; localStorage.setItem("user", JSON.stringify(data)); // Storing data const userData = JSON.parse(localStorage.getItem("user")); // Retrieving data console.log(userData.name); // Output: John
Using JSON methods to create a deep copy of an object (does not work for functions or circular references).
JSON.parse(text[, reviver]);
JSON | JavaScript Object |
---|---|
Text format (string) | In-memory data structure |
Keys must be strings (quoted) | Keys can be strings or symbols |
Cannot store methods/functions | Can store methods/functions |
Mastering JSON handling is a vital skill for building modern, data-driven web applications.
Hi, I'm Abhay Singh Kathayat!
I am a full-stack developer with expertise in both front-end and back-end technologies. I work with a variety of programming languages and frameworks to build efficient, scalable, and user-friendly applications.
Feel free to reach out to me at my business email: kaashshorts28@gmail.com.
The above is the detailed content of Mastering JSON Handling in JavaScript: Parsing and Stringifying. For more information, please follow other related articles on the PHP Chinese website!