Have you ever filled out a sign-up form on a website, hit submit, and wondered how your name and email actually travel from your browser all the way to the company’s server?
The answer, almost always, is JSON.
I remember the first time I opened my browser’s developer tools and saw a response full of curly braces and colons come back from a server. It looked scary at first, like some kind of secret code. But once I understood it, I realised it was just… data, written in a very simple, very readable way.
In this guide, we’ll go slow. You’ll learn what JSON actually is, why it exists, how to convert JavaScript into JSON and back again, and how it’s used in real projects like saving data in the browser or talking to a server.
What Is JSON, Really?
JSON stands for JavaScript Object Notation. In plain English, it’s just a way of writing down data as text, using a format that looks almost exactly like a JavaScript object.
Here’s a tiny example:
javascript
{
"name": "Riya",
"age": 21,
"isStudent": true
}
That’s it. That’s JSON. It’s just text, arranged in a pattern that both humans and computers can read easily.
Simple analogy: Think of JSON like a shipping label on a parcel. It doesn’t matter which courier company picks it up, or which country it’s going to everyone can read a shipping label because it follows the same simple format: sender name, address, weight, and so on. JSON works the same way for data. Any programming language Python, PHP, Java, JavaScript can read a JSON shipping label, even though each language stores data differently on the inside.
JSON vs a JavaScript Object
This is where most beginners get confused, so let’s clear it up right away.
- A JavaScript object is a real, living thing inside your program. You can call functions on it, check its type with
typeof, and use it directly in your code. - JSON is just text. It’s a string. It cannot have functions inside it, and you can’t directly use dot notation on it until you convert it back into a real JavaScript object.
They look almost identical, which is exactly why people mix them up. But one lives inside your program as a working object, and the other is a plain string of characters meant for storing or sending data.
Why Does JSON Even Exist?
Before JSON became popular, sending data between a browser and a server was messier. Developers used a format called XML, which works but is wordier and harder to read at a glance.
JSON caught on because it solves a very specific problem: how do you send structured data between two different systems that might be written in completely different programming languages?
Say your website’s frontend is built in JavaScript, but the backend server is written in PHP or Python. These two languages can’t directly hand a JavaScript object or a Python dictionary back and forth they speak different “languages” internally. But if you convert your data into a JSON string first, both sides can read it, because JSON is just plain text following an agreed-upon pattern.
This is why JSON is everywhere today:
- APIs (services that let apps talk to each other) almost always send and receive JSON
- Configuration files for apps and tools are often written in JSON
- Browsers use JSON to save small bits of data locally
- Mobile apps use JSON to communicate with their servers
If you’ve already read our guide on JavaScript Objects, you already understand most of what JSON borrows its structure from.
JSON Syntax Rules You Must Follow
JSON looks like a JavaScript object, but it’s actually stricter. It has its own rules, and breaking even one of them makes the JSON “invalid” meaning nothing can read it properly.
Rule 1: Keys Must Be in Double Quotes
In a JavaScript object, you can skip the quotes around property names. In JSON, you can’t.
javascript
// Valid JavaScript object
const user = { name: "Riya" };
// Valid JSON — key MUST be in double quotes
{ "name": "Riya" }
Rule 2: Strings Must Use Double Quotes, Not Single Quotes
JSON only accepts double quotes (") for text values. Single quotes (') will break it.
Rule 3: No Trailing Commas
If you leave an extra comma after the last item in an object or array, JSON will refuse to accept it.
javascript
// Invalid JSON — trailing comma after "age": 21
{ "name": "Riya", "age": 21, }
Rule 4: No Functions, No Comments, No undefined
JSON can only hold plain data. That means:
- No functions or methods
- No comments (
//or/* */) - No
undefined(onlynullis allowed for “empty” values)
Allowed Data Types in JSON
JSON only supports a small, fixed list of value types:
- Strings always in double quotes
- Numbers no quotes needed
- Booleans
trueorfalse - null represents “nothing”
- Objects
{ }for grouped data - Arrays
[ ]for lists of data
If you’re still getting comfortable with arrays, our guide on JavaScript Array Methods is a great companion to this one, since JSON uses arrays constantly.
JSON.stringify() – Turning JavaScript Into JSON
JSON.stringify() is a built-in function (a ready-made tool JavaScript gives you, so you don’t have to write it yourself) that takes a JavaScript object and converts it into a JSON string.
You’ll need this whenever you want to send data somewhere a server, a file, or the browser’s storage because those destinations only accept text, not live JavaScript objects.
javascript
const student = {
name: "Aman",
age: 19,
isEnrolled: true,
};
const jsonString = JSON.stringify(student);
console.log(jsonString);
// '{"name":"Aman","age":19,"isEnrolled":true}'
console.log(typeof jsonString);
// "string"
Notice the output is wrapped in quotes and printed on one line that’s your confirmation it’s now a plain string, not a live object anymore.
Making JSON.stringify() Output Readable
By default, JSON.stringify() squeezes everything onto one line. If you’re debugging or logging data for a human to read, you can pass two extra arguments to add spacing:
javascript
const jsonPretty = JSON.stringify(student, null, 2);
console.log(jsonPretty);
/*
{
"name": "Aman",
"age": 19,
"isEnrolled": true
}
*/
Here, null means “don’t filter out any properties,” and 2 means “use 2 spaces for indentation.” This trick is purely for readability it doesn’t change the actual data.
What Gets Left Out When You Stringify
JSON.stringify() quietly skips a few things it can’t represent in JSON:
- Properties with a value of
undefinedare removed entirely - Functions attached to the object are removed entirely
Symbolvalues are removed entirely
javascript
const data = {
name: "Aman",
greet: function () {
console.log("Hi!");
},
nickname: undefined,
};
console.log(JSON.stringify(data));
// '{"name":"Aman"}'
JSON.parse() – Turning JSON Back Into JavaScript
JSON.parse() does the exact opposite job. It takes a JSON string (maybe one you received from a server, or one you saved earlier) and converts it back into a real, usable JavaScript object.
You’ll need this whenever you receive data as text and want to actually work with it in your code use dot notation, loop through it, and so on.
javascript
const jsonString = '{"name":"Aman","age":19,"isEnrolled":true}';
const student = JSON.parse(jsonString);
console.log(student.name); // "Aman"
console.log(typeof student); // "object"
Simple analogy: If JSON.stringify() is like packing your data into a sealed envelope so it can be mailed, JSON.parse() is like opening that envelope back up on the other end so you can actually use what’s inside.
What Happens If the JSON Is Broken?
If the text you pass into JSON.parse() doesn’t follow proper JSON rules (say, it has single quotes or a trailing comma), it will throw an error and stop your program unless you catch it.
javascript
try {
const brokenJson = "{name: 'Aman'}"; // invalid JSON
const result = JSON.parse(brokenJson);
} catch (error) {
console.log("That JSON was invalid:", error.message);
}
Wrapping risky code in a try...catch block like this means one bad piece of data won’t crash your entire application.
Real-World Example: Saving Data with localStorage
One of the most common places you’ll use JSON as a beginner is browser storage. The browser’s localStorage can only save plain text strings it has no idea what a JavaScript array or object is. So whenever you want to save something more complex than a single string, you convert it to JSON first.
javascript
const cart = [
{ item: "Notebook", price: 40 },
{ item: "Pen", price: 10 },
];
// Saving: convert the array to a JSON string first
localStorage.setItem("cart", JSON.stringify(cart));
// Loading: convert the JSON string back into a real array
const savedCart = JSON.parse(localStorage.getItem("cart"));
console.log(savedCart[0].item); // "Notebook"
This pattern, stringify to save, parse to load, is something you’ll repeat constantly once you start building real projects.
Real-World Example: Sending and Receiving JSON with fetch()
If you’ve read our guide on JavaScript Promises, you’ve already seen fetch() in action. Here’s the part we didn’t focus on back then: what’s actually flowing back and forth is JSON.
Receiving JSON from a Server
When you request data from a server, it usually replies with a JSON string. That’s why you’ll almost always see .json() called on the response it parses that JSON text into a usable JavaScript object for you automatically.
javascript
fetch("https://jsonplaceholder.typicode.com/users/1")
.then((response) => response.json()) // parses the JSON response
.then((data) => {
console.log(data.name); // now it's a real JavaScript object
});
Sending JSON to a Server
When you want to send data to a server (say, submitting a form), you do the reverse: convert your JavaScript object into a JSON string using JSON.stringify() before sending it.
javascript
const newUser = { name: "Priya", age: 22 };
fetch("https://jsonplaceholder.typicode.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newUser), // convert object to JSON text before sending
})
.then((response) => response.json())
.then((data) => console.log("Server replied with:", data));
Notice the "Content-Type": "application/json" header this is you telling the server, “hey, the text I’m sending you is JSON, please read it that way.”
Common Beginner Mistakes
- Forgetting that JSON keys need double quotes. Writing
{name: "Aman"}looks fine in JavaScript but is invalid JSON. Always use{"name": "Aman"}. - Calling
.parse()when you meant.stringify()(or vice versa). A simple way to remember: Parse turns text into an object (Produces an object). Stringify turns an object into a String. - Forgetting to wrap
JSON.parse()in a try…catch. If the data you’re parsing is ever malformed even once, your app can crash without a safety net around it. - Trying to store a JavaScript object directly in localStorage.
localStorageonly accepts strings. Storing an object directly withoutJSON.stringify()will save the useless text"[object Object]"instead of your actual data.
Quick Comparison Table
| Concept | What It Does |
|---|---|
| JSON | A text-based format for storing and sending structured data |
JSON.stringify() | Converts a JavaScript object/array into a JSON string |
JSON.parse() | Converts a JSON string back into a JavaScript object/array |
| Double quotes | Required for all JSON keys and string values |
null | JSON’s way of representing “no value” (not undefined) |
localStorage | Browser storage that only accepts strings, so JSON is needed |
response.json() | A shortcut that parses a fetch() response’s JSON for you |
Scenario-Based Practice Problems
Scenario 1: You need to save a user’s theme preference (light or dark) in the browser so it stays saved after they close the tab.
Solution: Store it directly as a plain string since it’s a single simple value, JSON isn’t even required here.
javascript
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");
If the preference were an object instead, like { theme: "dark", fontSize: 16 }, then you would use JSON.stringify() to save it and JSON.parse() to load it back.
Scenario 2: Your app receives this JSON string from a server: '{"name":"Kabir","scores":[80,90,75]}'. You need to find the average score.
Solution: Parse it first, then work with the real array inside.
javascript
const jsonString = '{"name":"Kabir","scores":[80,90,75]}';
const student = JSON.parse(jsonString);
const total = student.scores.reduce((sum, score) => sum + score, 0);
const average = total / student.scores.length;
console.log(average); // 81.67 (approx)
Scenario 3: You have a JavaScript object with a function inside it, and you need to send it to a server as JSON.
Solution: Remember that JSON.stringify() automatically drops functions it can’t include them in JSON at all. Only the plain data properties will be sent, so make sure any logic you need is handled before stringifying, not inside the object itself.
Scenario 4: A user pastes JSON data into a text box on your app, but you’re not sure if what they typed is valid JSON.
Solution: Always parse untrusted or user-provided JSON inside a try...catch block, so a typo doesn’t crash your whole app.
javascript
function safeParse(text) {
try {
return JSON.parse(text);
} catch (error) {
console.log("Invalid JSON provided.");
return null;
}
}
Interview Questions
1. What is JSON, and how is it different from a JavaScript object?
JSON (JavaScript Object Notation) is a text-based format for representing structured data. A JavaScript object is a live, working value inside your code that can hold functions and other objects. JSON is just a string, following stricter formatting rules, meant for storing or transmitting data between systems.
2. What does JSON.stringify() do, and when would you use it?
JSON.stringify() converts a JavaScript object or array into a JSON string. You’d use it any time you need to send data to a server, save it in localStorage, or write it to a file all of which only accept text, not live objects.
3. What does JSON.parse() do, and what happens if the input is invalid?
JSON.parse() converts a JSON string back into a usable JavaScript object or array. If the string isn’t valid JSON, it throws an error, so it’s good practice to wrap it in a try...catch block, especially when the data is coming from an external source you don’t fully control.
4. Why can’t JSON store functions or undefined values?
JSON was designed to be a simple, language-independent data format. Functions are pieces of executable code tied to a specific language, and undefined is a JavaScript-only concept neither one translates cleanly into other programming languages, so JSON leaves them out entirely (they’re simply dropped during JSON.stringify()).
5. Why does JSON require double quotes around keys, while JavaScript objects don’t?
JSON was built to be strict and unambiguous so that any language, not just JavaScript, could reliably read it. Requiring double quotes removes any guesswork about where a key name starts and ends, which is essential when many different programming languages need to parse the exact same format consistently.
6. How would you save an array of objects in the browser using localStorage?
Since localStorage only stores strings, you’d first convert the array into a JSON string with JSON.stringify(), save that string, and then convert it back into a real array using JSON.parse() whenever you need to read it again.
Interview Tip: Interviewers often ask you to spot the bug in a broken JSON snippet (missing quotes, a trailing comma, single quotes instead of double). Practising by intentionally breaking and fixing small JSON examples is one of the fastest ways to build real confidence for this kind of question.
Frequently Asked Questions
Is JSON a programming language?
No. JSON is just a text-based data format, not a programming language. It has no logic, no loops, and no functions it only describes data using objects, arrays, strings, numbers, booleans, and null.
Can I use single quotes in JSON?
No. Valid JSON requires double quotes for both keys and string values. Single quotes will make the JSON invalid and cause JSON.parse() to throw an error.
What’s the difference between JSON.stringify() and JSON.parse()?
JSON.stringify() converts a JavaScript object into a JSON string (object to text). JSON.parse() does the opposite, converting a JSON string back into a usable JavaScript object (text to object).
Why does my localStorage show “[object Object]” instead of my data?
This happens when you try to save a JavaScript object directly into localStorage without converting it first. Since localStorage only accepts strings, JavaScript automatically converts your object into the unhelpful text "[object Object]". Always use JSON.stringify() before saving.
Does JSON support comments?
No. Standard JSON does not allow comments of any kind. If you need to store notes alongside your data, you’d need to add them as an actual property in the data itself, like "note": "explanation here".
Is JSON only used in JavaScript?
Not at all. Even though JSON stands for “JavaScript Object Notation,” it’s language-independent. Python, PHP, Java, and almost every modern programming language has built-in tools to read and write JSON, which is exactly why it’s become the standard for exchanging data across the web.
Trusted Sources & References
This guide is grounded in official documentation. For deeper reading on any of these topics, these are reliable places to go:
- MDN — Working with JSON a beginner-friendly overview of JSON and its purpose
- MDN — JSON.stringify() full technical reference for converting objects to JSON
- MDN — JSON.parse() full technical reference for converting JSON back to objects
- MDN — Window.localStorage official documentation on browser storage
- W3Schools — JSON Introduction beginner-friendly interactive examples
We recommend bookmarking MDN Web Docs it’s the most trusted, community-maintained reference for JavaScript and the web in general.
Continue Learning
Want to build on what you just learned? Check out these related guides on 28LazyCoder:
- JavaScript Objects: A Complete Beginner’s Guide with Examples
- JavaScript Promises Explained: A Complete Beginner’s Guide
- JavaScript Array Methods Explained: A Complete Beginner’s Guide with Examples
- JavaScript Functions: A Complete Guide with Examples
- JavaScript ES6 Features Explained: A Complete Beginner’s Guide
- var, let, and const: The Difference That Actually Matters
Explore more tutorials on 28LazyCoder.