JSON.stringify & JSON.parse

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.

Illustration of JSON.stringify & JSON.parse
Illustration of JSON.stringify & JSON.parse

💡 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

JAVASCRIPT
const user = { name: "Alice", age: 25, active: true };
const jsonString = JSON.stringify(user);
console.log(jsonString);
Output
{"name":"Alice","age":25,"active":true}

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

JAVASCRIPT
const jsonString = '{"name":"Alice","age":25,"active":true}';
const user = JSON.parse(jsonString);
console.log(user.name);  // Output: Alice
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.

Comparison: JSON.stringify vs JSON.parse
MethodPurpose
JSON.stringifyConverts JavaScript object/value → JSON string
JSON.parseConverts JSON string → JavaScript object/value

Additional Tips

  • JSON.stringify ignores functions, symbols, and undefined values.
  • Dates are serialized as ISO strings by JSON.stringify.
  • You can provide a replacer function or array to JSON.stringify to customize serialization.
  • JSON.parse accepts an optional reviver function to transform parsed values.

📌 Deep Dive: Using replacer and reviver

JAVASCRIPT
// 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
Output
{"name":"Bob","active":false}
true

💡 Summary

JSON.stringify turns objects into strings for storage or transmission. JSON.parse converts those strings back into usable JavaScript objects.