JSON in JavaScript
JSON stands for JavaScript Object Notation. It is a lightweight text format used to store and transfer data between a browser and a server.
Think of JSON like a shipping label. You need to send information from one place to another, and JSON gives you a standard format that both sides understand. Even though JSON was inspired by JavaScript, it works with almost every language — Python, PHP, Java, Go, and more.
Every time you use a web app that loads data — a weather widget, a product listing, a user profile — there is a very good chance JSON is involved behind the scenes.
// A JSON string — it is always a string
const jsonString = '{"name": "Alice", "age": 30, "isStudent": false}';
// Parse it into a real JavaScript object
const user = JSON.parse(jsonString);
console.log(user.name); // Alice
console.log(user.age); // 30
JSON looks a lot like a JavaScript object, but it is not the same thing. JSON is always a string. A JavaScript object is a live, in-memory structure. You convert between the two using JSON.parse() and JSON.stringify().
JSON has very strict formatting rules. One small mistake — an unquoted key, a trailing comma, a single quote instead of double — and it will not parse. The browser will throw a syntax error.
Here are the rules you must follow:
- Keys must always be in double quotes
- String values must also use double quotes
- No trailing commas after the last property
- No comments allowed inside JSON
- No undefined, no functions, no Date objects as values
// Valid JSON
{
"name": "Alice",
"age": 30,
"active": true,
"address": null
}
// Invalid JSON — key not quoted, trailing comma, single quotes
{
name: 'Alice',
age: 30,
}
A good habit is to validate your JSON using a free tool like jsonlint.com whenever you are writing it by hand. It catches issues immediately.
JSON supports exactly six value types. Unlike JavaScript, you cannot use functions, undefined, Symbol, or native Date objects as JSON values.
- String — must use double quotes: "hello"
- Number — integer or decimal: 42, 3.14
- Boolean — true or false
- Null — represents empty or unknown: null
- Array — an ordered list: [1, 2, 3]
- Object — key-value pairs: {"key": "value"}
// All six JSON data types
const json = `{
"name": "Alice",
"score": 98.5,
"passed": true,
"notes": null,
"tags": ["beginner", "js"],
"profile": { "city": "Delhi" }
}`;
const data = JSON.parse(json);
console.log(typeof data.name); // string
console.log(typeof data.score); // number
console.log(typeof data.passed); // boolean
console.log(data.notes); // null
console.log(Array.isArray(data.tags)); // true
console.log(typeof data.profile); // object
JSON.parse() converts a JSON string into a JavaScript object. You use this every time you receive data from a server — the raw response arrives as a string, and you need to turn it into an object before you can work with it.
const jsonString = '{"name": "Alice", "age": 30}';
const user = JSON.parse(jsonString);
console.log(user.name); // Alice
console.log(user.age); // 30
console.log(typeof user); // object
If the string is not valid JSON, JSON.parse() throws a SyntaxError. This can crash your application if you are not careful. Wrap it in a try/catch block when parsing data from an external source:
try {
const data = JSON.parse("this is not valid json");
} catch (e) {
console.error("Parsing failed:", e.message);
// Parsing failed: Unexpected token 'h', "this is "... is not valid JSON
}
JSON.parse() also accepts an optional reviver function as a second argument. This lets you transform values during parsing. For example, turning a date string back into a Date object:
const jsonStr = '{"name": "Alice", "joined": "2026-01-15T00:00:00.000Z"}';
const user = JSON.parse(jsonStr, (key, value) => {
if (key === "joined") return new Date(value);
return value;
});
console.log(user.name); // Alice
console.log(user.joined instanceof Date); // true
JSON.stringify() does the opposite of JSON.parse() — it converts a JavaScript object into a JSON string. You use this when you want to send data to a server or save it to localStorage.
const user = { name: "Alice", age: 30 };
const jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"Alice","age":30}'
console.log(typeof jsonString); // string
The third argument adds indentation, which makes the output easier to read:
const user = { name: "Alice", age: 30 };
const pretty = JSON.stringify(user, null, 2);
console.log(pretty);
// {
// "name": "Alice",
// "age": 30
// }
Functions and undefined values are silently dropped when you stringify. This will not throw an error — they simply disappear from the output:
const obj = {
name: "Alice",
greet: function() { return "hi"; },
score: undefined
};
console.log(JSON.stringify(obj)); // '{"name":"Alice"}'
// greet and score are silently dropped
The second argument is a replacer. Pass an array of key names to include only those keys in the output. This is useful when you want to send data without including sensitive fields:
const user = { name: "Alice", age: 30, password: "secret123" };
// Only include name and age — keep password out
const safe = JSON.stringify(user, ["name", "age"]);
console.log(safe); // '{"name":"Alice","age":30}'
JSON objects can contain other objects inside them. This is called nesting. You use it to represent structured data — like a user who has an address, which has a city and a zip code.
const jsonStr = `{
"name": "Alice",
"address": {
"city": "Delhi",
"zip": "110001",
"country": "India"
}
}`;
const user = JSON.parse(jsonStr);
console.log(user.address.city); // Delhi
console.log(user.address.zip); // 110001
console.log(user.address.country); // India
You can go as deep as you need. But very deeply nested JSON gets hard to read and maintain. If you find yourself going more than three or four levels deep, it is usually a sign the data structure needs rethinking.
const data = {
"user": {
"profile": {
"contact": {
"email": "alice@example.com"
}
}
}
};
// Access with dot notation
console.log(data.user.profile.contact.email); // alice@example.com
// Use optional chaining to avoid errors when a level is missing
console.log(data.user?.profile?.contact?.phone); // undefined — no crash
A JSON value can be an array. Arrays in JSON work exactly like JavaScript arrays — they hold an ordered list of values and you access items using their index.
const jsonStr = '{"students": ["Alice", "Bob", "Carol"]}';
const data = JSON.parse(jsonStr);
console.log(data.students[0]); // Alice
console.log(data.students.length); // 3
Arrays can also contain objects. This is the most common pattern you will see when fetching data from an API — a list of user objects, product objects, or post objects:
const jsonStr = `{
"users": [
{ "id": 1, "name": "Alice", "active": true },
{ "id": 2, "name": "Bob", "active": false },
{ "id": 3, "name": "Carol", "active": true }
]
}`;
const result = JSON.parse(jsonStr);
console.log(result.users[1].name); // Bob
console.log(result.users[2].active); // true
// Loop through the array
result.users.forEach(user => {
console.log(user.name, user.active ? "active" : "inactive");
});
// Alice active
// Bob inactive
// Carol active
You can also have a top-level JSON array — the entire JSON is just an array, not wrapped in an object:
const jsonStr = '[1, 2, 3, 4, 5]';
const numbers = JSON.parse(jsonStr);
console.log(numbers[0]); // 1
console.log(numbers.length); // 5
JSON and JavaScript objects look almost identical, which causes a lot of confusion. But they are not the same thing. Here are the key differences:
- Keys: In JSON, keys must be in double quotes. In a JS object, keys can be unquoted.
- Values: JSON supports only 6 types. A JS object can hold functions, undefined, Symbols, and more.
- Functions: Not allowed in JSON. Silently dropped by JSON.stringify().
- undefined: Not valid in JSON. Silently dropped by JSON.stringify().
- Type: JSON is always a string. A JS object is a live data structure in memory.
- Comments: Not allowed in JSON. Fine in JavaScript code.
// JavaScript Object — flexible, lives in memory
const user = {
name: "Alice", // unquoted key — valid in JS
age: 30,
greet() { return "hi"; } // function — not allowed in JSON
};
// JSON — always a string, strict format
const json = '{"name": "Alice", "age": 30}';
// Convert between them
const obj = JSON.parse(json); // JSON string => JS object
const str = JSON.stringify(user); // JS object => JSON string
console.log(str); // '{"name":"Alice","age":30}' — greet() is silently dropped
- JSON (JavaScript Object Notation) is a text format for storing and transferring data. It works across almost every programming language.
- JSON syntax rules: Keys must be in double quotes. No trailing commas, no comments, no functions, no undefined.
- JSON data types: string, number, boolean, null, array, object — that is all. No functions or Date objects.
- JSON.parse(): Converts a JSON string into a JavaScript object. Throws a SyntaxError if the input is invalid — always use try/catch with untrusted input.
- JSON.stringify(): Converts a JavaScript object into a JSON string. Functions and undefined are silently dropped. Use the replacer and space arguments to control output.
- Nested JSON: Objects can contain other objects. Access nested values with dot notation. Use optional chaining to avoid crashes on missing levels.
- JSON arrays: Arrays can hold strings, numbers, or full objects. Very common when fetching a list of items from an API.
- JSON vs object: JSON is always a string. A JS object is live in-memory data. JSON keys must be in double quotes; JS object keys do not need quotes.
- What is JSON and why is it used for data exchange?
- What are the six valid data types in JSON?
- What is the difference between JSON.parse() and JSON.stringify()?
- What happens if you call JSON.stringify() on an object that has a function as a property?
- What is the difference between a JSON string and a JavaScript object?
- How would you safely parse JSON that might be invalid?
- What does the third argument of JSON.stringify() do?
- How do you access values from a deeply nested JSON structure?
- Why are trailing commas and comments not allowed in JSON?
- How would you convert a JavaScript object to JSON and save it to localStorage?