When JavaScript applications communicate with servers, they often need to send and receive data.
For example, a server might send user information like this:
{
"name": "John",
"age": 25,
"city": "Delhi"
}This format is called JSON.
JSON is extremely common in web development because it provides a simple way to exchange structured data between different systems.
What is JSON?
JSON stands for JavaScript Object Notation.
It is a lightweight text-based format used to store and exchange structured data.
Despite its name, JSON isn't limited to JavaScript. Almost every modern programming language can work with JSON.
For example, a JavaScript application can receive JSON from a Python, Java, PHP, Node.js, or any other backend server.
JSON vs JavaScript Object
JSON looks very similar to a JavaScript object, but they aren't exactly the same.
A JavaScript object:
const user = {
name: "John",
age: 25
};JSON:
{
"name": "John",
"age": 25
}Notice that JSON requires property names to be enclosed in double quotes.
Also, JSON is ultimately text, while a JavaScript object is an actual JavaScript value.
JSON Data Types
JSON supports a limited set of data types:
JSON Type | Example |
|---|---|
String |
|
Number |
|
Boolean |
|
Object |
|
Array |
|
Null |
|
JSON does not support JavaScript-specific values such as:
undefined
function
Symbol
BigIntJSON Strings
Strings in JSON must use double quotes.
Valid JSON:
{
"name": "John"
}This is not valid JSON:
{
'name': 'John'
}Single quotes are commonly used in JavaScript, but JSON requires double quotes for strings and property names.
JSON Objects
A JSON object contains key-value pairs.
{
"name": "John",
"age": 25,
"isStudent": true
}Here we have:
name → "John"
age → 25
isStudent → trueObjects can also contain nested objects:
{
"name": "John",
"address": {
"city": "Delhi",
"country": "India"
}
}JSON Arrays
JSON also supports arrays.
{
"name": "John",
"skills": [
"JavaScript",
"HTML",
"CSS"
]
}We can also have an array of objects:
[
{
"name": "John",
"age": 25
},
{
"name": "Alex",
"age": 22
}
]This structure is very common in API responses.
JSON.stringify()
JavaScript provides the JSON object with methods for converting between JavaScript values and JSON.
The first important method is:
JSON.stringify()It converts a JavaScript value into a JSON string.
For example:
const user = {
name: "John",
age: 25
};
const jsonData = JSON.stringify(user);
console.log(jsonData);Output:
{"name":"John","age":25}Notice that the result is now a string.
We can check:
console.log(typeof jsonData);Output:
stringWhy Use JSON.stringify()?
One common use is sending data to a server.
For example:
const user = {
name: "John",
age: 25
};
const data = JSON.stringify(user);The resulting JSON string can then be included in an HTTP request body.
It's also useful when storing objects in localStorage, because Web Storage stores strings:
localStorage.setItem("user", JSON.stringify(user));JSON.parse()
The opposite of JSON.stringify() is:
JSON.parse()It converts a valid JSON string back into a JavaScript value.
For example:
const jsonData = '{"name":"John","age":25}';
const user = JSON.parse(jsonData);
console.log(user.name);
console.log(user.age);Output:
John
25Now user is a normal JavaScript object.
stringify() vs parse()
This is one of the most important things to remember.
JavaScript Object
↓
JSON.stringify()
↓
JSON StringAnd the reverse:
JSON String
↓
JSON.parse()
↓
JavaScript ObjectA simple memory trick:
Stringify → Turn it into a string
Parse → Read a JSON string back into a value
Working with JSON Arrays
JSON.stringify() and JSON.parse() also work with arrays.
const fruits = ["Apple", "Banana", "Mango"];
const jsonData = JSON.stringify(fruits);
console.log(jsonData);Output:
["Apple","Banana","Mango"]We can convert it back:
const result = JSON.parse(jsonData);
console.log(result[0]);Output:
AppleJSON and APIs
JSON is heavily used when working with APIs.
For example, an API might return:
{
"id": 101,
"name": "John",
"email": "john@example.com"
}JavaScript can receive this data and work with it like a normal object.
A common example using fetch() is:
async function getUser() {
const response = await fetch("/api/user");
const user = await response.json();
console.log(user.name);
}Notice something interesting here:
response.json()This reads the response body and parses JSON into a JavaScript value.
You don't normally need to manually call JSON.parse() when using response.json().
Sending JSON to an API
When sending data to a server, we commonly convert a JavaScript object into JSON.
const user = {
name: "John",
age: 25
};
fetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(user)
});Here:
JavaScript object
↓
JSON.stringify()
↓
JSON text
↓
Sent to serverThe Content-Type header tells the server that the request body contains JSON.
JSON Formatting
JSON can be written on one line:
{"name":"John","age":25,"city":"Delhi"}Or formatted across multiple lines:
{
"name": "John",
"age": 25,
"city": "Delhi"
}Both represent the same data.
The second format is simply easier for humans to read.
Pretty Printing JSON
JSON.stringify() can also format JSON nicely.
For example:
const user = {
name: "John",
age: 25,
city: "Delhi"
};
console.log(JSON.stringify(user, null, 2));Output:
{
"name": "John",
"age": 25,
"city": "Delhi"
}The 2 specifies the indentation size.
This is useful when displaying or debugging JSON.
Handling Invalid JSON
JSON.parse() throws an error if the provided string isn't valid JSON.
For example:
try {
const data = JSON.parse("Hello World");
} catch (error) {
console.log("Invalid JSON.");
}Output:
Invalid JSON.This is one situation where the error-handling concepts we learned earlier become useful.
Common JSON Mistakes
Using Single Quotes
❌ Invalid:
{
'name': 'John'
}✅ Valid:
{
"name": "John"
}Trailing Commas
❌ Invalid:
{
"name": "John",
"age": 25,
}JSON does not allow a trailing comma.
Using undefined
❌ Invalid JSON value:
const user = {
name: "John",
age: undefined
};JSON has no undefined type.
Using Functions
JSON cannot directly represent JavaScript functions:
const user = {
name: "John",
greet() {
console.log("Hello");
}
};The function isn't represented as a normal JSON value.
A Practical Example
Let's say we're building a student application.
We have a JavaScript object:
const student = {
name: "John",
age: 21,
course: "Computer Science",
skills: ["JavaScript", "HTML", "CSS"]
};We can convert it to JSON:
const jsonStudent = JSON.stringify(student);
console.log(jsonStudent);Now imagine this JSON is stored or sent to a server.
Later, we can convert it back:
const studentData = JSON.parse(jsonStudent);
console.log(studentData.name);
console.log(studentData.skills[0]);Output:
John
JavaScriptThis simple process is at the heart of a huge amount of data exchange in web applications.
Conclusion
JSON is a lightweight format used to store and exchange structured data. You'll encounter it constantly when working with APIs, servers, configuration data, and browser storage.
The two most important methods are:
JSON.stringify()Converts a JavaScript value into a JSON string.
JSON.parse()Converts a JSON string back into a JavaScript value.
Remember the flow:
JavaScript Object
↓
JSON.stringify()
↓
JSON String
↓
API / Storage
↓
JSON.parse()
↓
JavaScript ObjectOnce you're comfortable with JSON, you'll be much better prepared for the next major JavaScript concept: Asynchronous JavaScript, where we'll learn how JavaScript handles operations such as API requests that don't finish immediately.