JSON
JSON (JavaScript Object Notation) is a text format for sending and saving data. It looks like a JavaScript object but is always a string when traveling over the network.
What is JSON?
JSON (JavaScript Object Notation) is a text format for sending and saving data. It looks like a JavaScript object but is always a string when traveling over the network.
Real-life example: JSON is like a packed lunch box with labels — name, rice, curry — written in a standard format every school understands.
- Keys must be in double quotes.
- Values can be string, number, boolean, null, array, or object.
- No functions, comments, or trailing commas in strict JSON.
JSON.stringify
JSON.stringify turns a JavaScript value into a JSON string. Send it to a server or save it in localStorage.
Real-life example: Packing clothes into a suitcase (string) before a flight — you cannot wear them on the plane until you unpack at the hotel.
const user = { name: "Asha", grade: 10, active: true };
const jsonText = JSON.stringify(user);
console.log(jsonText);
// {"name":"Asha","grade":10,"active":true}
JSON.stringify(user, null, 2); // pretty print with 2-space indentJSON.parse
JSON.parse turns a JSON string back into a JavaScript object or array.
Real-life example: Opening the suitcase at the hotel — string becomes usable clothes (object) again.
const text = '{"course":"JavaScript","lesson":19}';
const data = JSON.parse(text);
console.log(data.course); // JavaScript
try {
JSON.parse("{ bad json }");
} catch (e) {
console.error("Invalid JSON:", e.message);
}Common API payload shape
Most APIs return JSON with a predictable shape: a success flag, a data field, and sometimes an error message.
Real-life example: A pizza delivery app reply — status: "on the way", data: { orderId, eta }, error: null. Same pattern every time makes coding easier.
// What many REST APIs return
const apiResponse = {
success: true,
data: {
courses: [
{ id: 1, title: "HTML & CSS", slug: "html-css-zero-to-hero" },
{ id: 2, title: "JavaScript", slug: "javascript-fundamentals" },
],
},
error: null,
};
const courses = apiResponse.data.courses;JSON vs JavaScript object
A JS object can hold functions, undefined, and symbols. JSON is stricter — text only, for sharing between systems.
Real-life example: A JS object is your full diary with doodles and phone numbers. JSON is the typed page you email — only plain facts, no secrets scribbled in margins.
const jsObject = {
name: "Ravi",
greet() { return "Hi"; }, // functions — OK in JS, NOT in JSON
extra: undefined, // undefined — OK in JS, NOT in JSON
};
// JSON.stringify skips functions and undefined keys
JSON.stringify(jsObject); // {"name":"Ravi"}