JavaScript JSON – parse() and stringify()


JSON (JavaScript Object Notation) is a popular format for storing and exchanging data, especially between a client and server in APIs.

JavaScript has two built-in methods to work with JSON:

  • JSON.stringify() – Converts JavaScript object to JSON string
  • JSON.parse() – Converts JSON string back to JavaScript object


1. JSON.stringify() – Object ➝ JSON String


Example:

const user = {
  name: "Alice",
  age: 25,
  city: "New York"
};

const jsonString = JSON.stringify(user);
console.log(jsonString);

Output

{"name":"Alice","age":25,"city":"New York"}

Use When: Sending data to a server or saving in localStorage.



2. JSON.parse() – JSON String ➝ Object


Example:

const jsonData = '{"name":"Alice","age":25,"city":"New York"}';
const userObj = JSON.parse(jsonData);
console.log(userObj.name);

Output

Alice

Use When: Receiving data from a server (API response).



Real-World Use Case: localStorage

// Save to localStorage
localStorage.setItem("user", JSON.stringify(user));

// Get from localStorage
const data = localStorage.getItem("user");
const parsedUser = JSON.parse(data);
console.log(parsedUser.age);  // 25


Important Notes

  • JSON.stringify() skips functions, undefined, and symbols.
  • JSON.parse() only works on valid JSON (double quotes only).
  • You can format output using a third parameter in stringify():
console.log(JSON.stringify(user, null, 2));  // pretty print


Bonus: Handle Errors with try...catch

try {
  const data = JSON.parse('{"name": "John"');
} catch (error) {
  console.log("Invalid JSON:", error.message);
}