In JavaScript, JSON.stringify and JSON.parse are two essential methods used to convert data between JavaScript objects and JSON strings. Understanding these methods is key to handling data interchange, especially when working with APIs or storing data.

💡 What is JSON?
JSON (JavaScript Object Notation) is a lightweight data format that is easy for humans to read and write, and easy for machines to parse and generate. It represents data as text.
JSON.stringify
JSON.stringify converts a JavaScript object or value to a JSON-formatted string.
- Useful for sending data to a server or saving it as text
- Can accept additional arguments for filtering or formatting
📌 Deep Dive: Using JSON.stringify
const user = { name: "Alice", age: 25, active: true };
const jsonString = JSON.stringify(user);
console.log(jsonString);
JSON.parse
JSON.parse converts a JSON-formatted string back into a JavaScript object or value.
- Used when receiving JSON data as text (e.g., from an API)
- Throws an error if the string is not valid JSON
📌 Deep Dive: Using JSON.parse
const jsonString = '{"name":"Alice","age":25,"active":true}';
const user = JSON.parse(jsonString);
console.log(user.name); // Output: Alice
⚠️ Common Pitfall
Passing a non-string or invalid JSON string to JSON.parse will cause a runtime error. Always ensure the string is valid JSON before parsing.
| Method | Purpose |
|---|---|
| JSON.stringify | Converts JavaScript object/value → JSON string |
| JSON.parse | Converts JSON string → JavaScript object/value |
Additional Tips
JSON.stringifyignores functions, symbols, and undefined values.- Dates are serialized as ISO strings by
JSON.stringify. - You can provide a replacer function or array to
JSON.stringifyto customize serialization. JSON.parseaccepts an optional reviver function to transform parsed values.
📌 Deep Dive: Using replacer and reviver
// Replacer example: exclude 'age' property
const user = { name: "Bob", age: 30, active: false };
const jsonString = JSON.stringify(user, ['name', 'active']);
console.log(jsonString); // {"name":"Bob","active":false}
// Reviver example: convert date string back to Date object
const jsonDate = '{"event":"meeting","date":"2024-06-01T10:00:00.000Z"}';
const obj = JSON.parse(jsonDate, (key, value) => {
if (key === 'date') return new Date(value);
return value;
});
console.log(obj.date instanceof Date); // true
true
💡 Summary
JSON.stringify turns objects into strings for storage or transmission. JSON.parse converts those strings back into usable JavaScript objects.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What does JSON.stringify do?
Question 2 of 2
Which of the following will cause JSON.parse to throw an error?
Loading results...