JavaScript JSON
Learn how JSON works in JavaScript. Master JSON syntax, objects, arrays, nested data, JSON.parse(), JSON.stringify(), replacers, revivers, formatting, validation, deep copying, API data, and real-world data handling.
Introduction
Modern applications constantly exchange and store data. A website may receive user information from a server, send form data to an API, save application settings in browser storage, load configuration from a file, or communicate with another application.
For different systems to exchange information successfully, they need a common data format. One of the most widely used formats for this purpose is JSON.
JSON is used everywhere in modern development. Frontend applications receive JSON from APIs, backend applications send JSON responses, configuration files often use JSON, and browser storage commonly stores objects after converting them to JSON strings.
- What JSON is.
- Why JSON is used.
- The difference between JSON and JavaScript objects.
- The syntax rules of JSON.
- Which data types JSON supports.
- How JSON strings work.
- How JSON numbers work.
- How JSON booleans work.
- How null works in JSON.
- How JSON objects are structured.
- How JSON arrays are structured.
- How nested JSON works.
- How to identify valid and invalid JSON.
- How JSON.parse() works.
- How to convert JSON strings into JavaScript values.
- How to handle invalid JSON.
- How the reviver function works.
- How to restore date strings as Date objects.
- How JSON.stringify() works.
- How to convert JavaScript values into JSON strings.
- How replacer functions work.
- How replacer arrays work.
- How to format JSON output.
- How unsupported JavaScript values behave.
- How undefined behaves during serialization.
- How functions and symbols behave.
- How NaN and Infinity behave.
- How BigInt interacts with JSON.
- How Date objects are serialized.
- How toJSON() works.
- Why circular references cause errors.
- How JSON can be used for deep copying.
- The limitations of JSON-based deep copying.
- How JSON works with browser storage.
- How JSON is used with APIs.
- How to receive JSON data.
- How to send JSON data.
- How fetch() works with JSON.
- How JSON files are structured.
- How to safely validate and parse JSON.
- How to work with optional JSON properties.
- How to destructure JSON data.
- How to iterate through JSON data.
- How to filter, map, search, and sort JSON data.
- How to build a complete JSON-based application.
What is JSON?
JSON stands for JavaScript Object Notation. It is a lightweight text-based format used to represent and exchange structured data.
Although JSON syntax was inspired by JavaScript object syntax, JSON is not a JavaScript object. JSON is text.
{ "name": "Aarav", "age": 25, "isStudent": false}This JSON text represents information about a user. The same data can be transmitted over a network, stored in a file, saved in browser storage, or converted into a JavaScript object.
- JSON is a text format.
- JSON represents structured data.
- JSON is language-independent.
- JSON is commonly used for data exchange.
- JSON syntax is based on key-value pairs and arrays.
Why Do We Need JSON?
API Communication
Web applications commonly send and receive JSON data through APIs.
Data Storage
Structured data can be stored as JSON text in files and browser storage.
Data Exchange
Different programming languages can exchange data using the same JSON format.
Configuration
Applications and development tools often use JSON configuration files.
Lightweight Format
JSON is compact, readable, and easy for applications to process.
Structured Data
Objects, arrays, strings, numbers, booleans, and null can be combined into complex structures.
Real-World Analogy
Imagine two people who speak different languages but agree to exchange information using the same standardized form. Each person can read the form, translate it into their own language, process the information, and create another standardized form as a response.
APPLICATION A(JavaScript)
JavaScript Object │ ▼Convert to JSON │ ▼
┌─────────────────────────┐│ JSON TEXT ││ ││ { ││ "name": "Aarav", ││ "age": 25 ││ } │└────────────┬────────────┘ │ ▼ Send Data │ ▼
APPLICATION B(Java / Python / PHP / C#)
Receive JSON │ ▼Convert to Native Data │ ▼Process InformationJSON vs JavaScript Object
JSON and JavaScript objects may look similar, but they are not the same.
const user = { name: 'Aarav', age: 25, isStudent: false};
console.log( typeof user);Click Run to see what this code prints.
const jsonText = `{ "name": "Aarav", "age": 25, "isStudent": false}`;
console.log( typeof jsonText);Click Run to see what this code prints.
This code should show that user is an object and json is a string, but json was never actually converted. Fix it so it logs 'object' then 'string'.
JAVASCRIPT OBJECT
{ name: 'Aarav', age: 25}
Type:object
Keys:Quotes usually optional
Strings:Single or double quotes allowed
Can Contain:FunctionsundefinedSymbolsOther JavaScript values
JSON
{ "name": "Aarav", "age": 25}
Type:Text / string
Keys:Double quotes required
Strings:Double quotes required
Can Contain:ObjectArrayStringNumberBooleannullJSON Syntax Rules
- JSON data is written using objects and arrays.
- Object property names must use double quotes.
- String values must use double quotes.
- Key-value pairs are separated by commas.
- Keys and values are separated by colons.
- Objects use curly braces.
- Arrays use square brackets.
- JSON does not support comments.
- JSON does not support trailing commas.
- JSON does not support undefined.
- JSON does not support functions.
- JSON does not support symbols.
- JSON supports strings, numbers, booleans, null, objects, and arrays.
{ "name": "Aarav", "age": 25, "skills": [ "HTML", "CSS", "JavaScript" ], "active": true, "address": null}JSON Data Types
String
Text enclosed in double quotes.
Number
Integer or decimal numeric values.
Boolean
The values true or false.
null
Represents an intentional empty value.
Object
A collection of key-value pairs.
Array
An ordered collection of values.
{ "name": "JavaScript", "year": 1995, "popular": true, "creator": { "name": "Brendan Eich" }, "uses": [ "Web", "Server", "Mobile" ], "deprecated": null}JSON Strings
JSON strings must always be enclosed in double quotes.
{ "name": "JavaScript", "message": "Hello, World!", "country": "India"}VALID
"JavaScript"
INVALID JSON
'JavaScript'
VALID
{ "name": "Aarav"}
INVALID JSON
{ 'name': 'Aarav'}Special characters inside JSON strings must be escaped when necessary.
{ "message": "He said, \"Hello!\"", "path": "C:\\Users\\Student", "text": "Line 1\nLine 2"}JSON Numbers
JSON supports numeric values without quotes.
{ "age": 25, "price": 499.99, "temperature": -5, "population": 1400000000}- Numbers must not be enclosed in quotes if they should remain numeric.
- JSON does not support NaN.
- JSON does not support Infinity.
- JSON does not support -Infinity.
- Large numbers may require special handling because JavaScript number precision has limits.
JSON Booleans
{ "isLoggedIn": true, "isAdmin": false}The values true and false are written without quotes and use lowercase letters.
JSON null
The null value represents an intentional absence of a value.
{ "middleName": null, "profileImage": null}JSON Objects
A JSON object is enclosed in curly braces and contains key-value pairs.
{ "name": "Aarav", "age": 25, "city": "Mumbai"}{ "name": "Aarav", "age": 25} │ │ │ └── Value │ └── Key
KEY-VALUE PAIR
"name": "Aarav" │ │ │ └── Value │ └── Property NameJSON Arrays
A JSON array is an ordered collection of values enclosed in square brackets.
[ "HTML", "CSS", "JavaScript"][ { "id": 1, "name": "Aarav" }, { "id": 2, "name": "Diya" }, { "id": 3, "name": "Kabir" }]Nested JSON
JSON objects and arrays can contain other objects and arrays, allowing complex data structures to be represented.
{ "name": "Aarav", "address": { "city": "Mumbai", "state": "Maharashtra", "country": "India" }, "skills": [ "HTML", "CSS", "JavaScript" ]}Complex JSON Structure
{ "course": { "id": 101, "title": "Core JavaScript", "free": true, "instructor": { "name": "PrograMinds", "experience": 10 }, "topics": [ { "id": 1, "title": "Introduction", "completed": true }, { "id": 2, "title": "History", "completed": true }, { "id": 3, "title": "JavaScript Engine", "completed": false } ], "rating": 4.8, "certificate": null }}ROOT OBJECT │ ▼ course │ ├── id ├── title ├── free │ ├── instructor │ │ │ ├── name │ └── experience │ ├── topics │ │ │ ├── Topic Object │ ├── Topic Object │ └── Topic Object │ ├── rating └── certificateValid and Invalid JSON
{ "name": "Aarav", "age": 25}{ name: "Aarav"}{ 'name': 'Aarav'}{ "name": "Aarav", "age": 25,}{ // User name "name": "Aarav"}- Property names require double quotes.
- String values require double quotes.
- Comments are not allowed.
- Trailing commas are not allowed.
- JavaScript expressions are not allowed.
- Functions are not allowed.
- undefined is not allowed.
JSON.parse()
The JSON.parse() method converts valid JSON text into a JavaScript value.
const jsonText = '{"name":"Aarav","age":25}';
const user = JSON.parse( jsonText );
console.log(user);
console.log( typeof user);Click Run to see what this code prints.
Parsing JSON Objects
const jsonText = `{ "name": "Diya", "age": 22, "active": true}`;
const user = JSON.parse( jsonText );
console.log( user.name);
console.log( user.age);
console.log( user.active);Click Run to see what this code prints.
Fix the code so it correctly parses the JSON text before reading the name and age properties from it.
Parsing JSON Arrays
const jsonText = '["HTML","CSS","JavaScript"]';
const skills = JSON.parse( jsonText );
console.log( skills[0]);
console.log( skills.length);Click Run to see what this code prints.
Accessing Parsed Data
const jsonText = `{ "name": "Aarav", "address": { "city": "Mumbai", "country": "India" }, "skills": [ "JavaScript", "React", "Node.js" ]}`;
const user = JSON.parse( jsonText );
console.log( user.name);
console.log( user.address.city);
console.log( user.skills[1]);Click Run to see what this code prints.
Handling Parse Errors
JSON.parse() throws a SyntaxError when the input is not valid JSON. For data from external sources, parsing should be handled carefully.
const jsonText = '{"name":"Aarav",}';
const user = JSON.parse( jsonText );Click Run to see what this code prints.
const jsonText = '{"name":"Aarav",}';
try { const user = JSON.parse( jsonText );
console.log(user);} catch (error) { console.log( 'Invalid JSON data' );
console.log( error.message );}JSON Parse Flow
JSON TEXT
"{\"name\":\"Aarav\",\"age\":25}"
│ ▼
JSON.parse()
│ ┌──────┴──────┐ ▼ ▼ Valid JSON Invalid JSON │ │ ▼ ▼JavaScript SyntaxError Value │ ▼
{ name: "Aarav", age: 25}The Reviver Function
JSON.parse() accepts an optional second argument called a reviver. The reviver function can inspect and transform values while JSON is being converted into JavaScript data.
const jsonText = `{ "name": "Aarav", "age": 25}`;
const user = JSON.parse( jsonText,
function (key, value) { console.log( key, value );
return value; } );
console.log(user);Converting Date Strings
JSON does not have a Date data type. Dates are usually stored as strings. A reviver can convert selected date strings back into Date objects.
const jsonText = `{ "name": "Aarav", "joinedAt": "2026-07-09T10:30:00.000Z"}`;
const user = JSON.parse( jsonText,
function (key, value) { if ( key === 'joinedAt' ) { return new Date( value ); }
return value; } );
console.log( user.joinedAt);
console.log( user.joinedAt instanceof Date);Click Run to see what this code prints.
Transforming Values During Parsing
const jsonText = `{ "name": "aarav", "score": 80}`;
const data = JSON.parse( jsonText,
function (key, value) { if ( key === 'name' ) { return value .toUpperCase(); }
if ( key === 'score' ) { return value + 10; }
return value; } );
console.log(data);Click Run to see what this code prints.
JSON.stringify()
The JSON.stringify() method converts a JavaScript value into JSON text.
const user = { name: 'Aarav', age: 25, active: true};
const jsonText = JSON.stringify( user );
console.log(jsonText);
console.log( typeof jsonText);Click Run to see what this code prints.
Fix the code so json actually holds a JSON string produced by JSON.stringify(), instead of a string created by concatenating the object.
Stringifying Objects
const course = { title: 'Core JavaScript', lessons: 27, free: true};
const json = JSON.stringify( course );
console.log(json);Click Run to see what this code prints.
Stringifying Arrays
const skills = [ 'HTML', 'CSS', 'JavaScript'];
const json = JSON.stringify( skills );
console.log(json);Click Run to see what this code prints.
Stringifying Nested Data
const user = { name: 'Aarav',
address: { city: 'Mumbai', country: 'India' },
skills: [ 'JavaScript', 'React' ]};
const json = JSON.stringify( user );
console.log(json);The Replacer Function
JSON.stringify() accepts an optional replacer function that can transform or remove values during serialization.
const user = { name: 'Aarav', age: 25, password: 'secret123'};
const json = JSON.stringify( user,
function (key, value) { if ( key === 'password' ) { return undefined; }
return value; } );
console.log(json);Click Run to see what this code prints.
The replacer function should remove the password field, but it currently removes the email field instead. Fix the condition.
const product = { name: 'Laptop', price: 50000};
const json = JSON.stringify( product,
function (key, value) { if ( key === 'price' ) { return value * 0.9; }
return value; } );
console.log(json);The Replacer Array
An array can be passed as the second argument to JSON.stringify() to select which properties should be included.
const user = { id: 101, name: 'Aarav', age: 25, password: 'secret123', role: 'student'};
const json = JSON.stringify( user, [ 'id', 'name', 'role' ] );
console.log(json);Click Run to see what this code prints.
Formatting JSON Output
By default, JSON.stringify() produces compact JSON. A third argument can add indentation and make the output easier for humans to read.
const user = { name: 'Aarav', age: 25, skills: [ 'JavaScript', 'React' ]};
const json = JSON.stringify( user, null, 2 );
console.log(json);Click Run to see what this code prints.
The space Argument
JSON.stringify( data, null, 2);
JSON.stringify( data, null, 4);
JSON.stringify( data, null, '\t');JSON.stringify( value, replacer, space);
value
The JavaScript valueto serialize.
replacer
Optional transformationor property selection.
space
Optional indentationfor readable output.JSON Stringify Flow
JAVASCRIPT VALUE
{ name: "Aarav", age: 25}
│ ▼
JSON.stringify()
│ ▼
JSON TEXT
"{\"name\":\"Aarav\",\"age\":25}"
│ ▼
Can Be:
Sent to APIStored in BrowserSaved in FileTransferred to Another SystemUnsupported Values
JavaScript supports more value types than JSON. When JavaScript data is converted to JSON, unsupported values may be omitted, converted, or cause an error.
undefined in JSON
const user = { name: 'Aarav', age: undefined};
console.log( JSON.stringify( user ));Click Run to see what this code prints.
Object properties containing undefined are omitted.
const values = [ 10, undefined, 30];
console.log( JSON.stringify( values ));Click Run to see what this code prints.
Fix the code so it logs the stringified JSON (with the undefined property omitted), not the raw settings object.
Functions in JSON
const user = { name: 'Aarav',
greet: function () { return 'Hello'; }};
console.log( JSON.stringify( user ));Click Run to see what this code prints.
Functions are not part of the JSON data model and object properties containing functions are omitted during serialization.
Symbols in JSON
const id = Symbol('id');
const user = { name: 'Aarav', code: id};
console.log( JSON.stringify( user ));Click Run to see what this code prints.
NaN and Infinity
const values = { first: NaN, second: Infinity, third: -Infinity};
console.log( JSON.stringify( values ));Click Run to see what this code prints.
BigInt and JSON
JSON.stringify() cannot directly serialize a BigInt value and normally throws a TypeError.
const data = { value: 12345678901234567890n};
JSON.stringify( data);Click Run to see what this code prints.
const data = { value: 12345678901234567890n};
const json = JSON.stringify( data,
function (key, value) { if ( typeof value === 'bigint' ) { return value .toString(); }
return value; } );
console.log(json);Date Objects and JSON
Date objects are converted into ISO-formatted strings during JSON serialization.
const event = { title: 'JavaScript Class', date: new Date( '2026-07-09T10:30:00Z' )};
const json = JSON.stringify( event );
console.log(json);Click Run to see what this code prints.
- JSON has no Date data type.
- Date objects are serialized as strings.
- Parsing the JSON does not automatically restore a Date object.
- A reviver or manual conversion is required to restore Date behavior.
toJSON() Method
If an object defines a toJSON() method, JSON.stringify() uses the value returned by that method.
const user = { id: 101, name: 'Aarav', password: 'secret123',
toJSON() { return { id: this.id, name: this.name }; }};
console.log( JSON.stringify( user ));Click Run to see what this code prints.
Circular References
A circular reference occurs when an object eventually refers back to itself. Standard JSON serialization cannot represent circular references.
const user = { name: 'Aarav'};
user.self = user;
JSON.stringify( user);Click Run to see what this code prints.
user │ ├── name │ └── self │ └──────────────┐ │ ▼ user
Infinite Reference LoopDeep Copy with JSON
A common historical technique for copying simple JSON-compatible data is to stringify the value and then parse the result.
const original = { name: 'Aarav',
address: { city: 'Mumbai' }};
const copy = JSON.parse( JSON.stringify( original ) );
copy.address.city = 'Pune';
console.log( original.address.city);
console.log( copy.address.city);Click Run to see what this code prints.
The spread operator only makes a shallow copy, so the nested address object is still shared. Fix the code so copy is a true deep copy and modifying it does not affect original.
Limitations of JSON Deep Copy
- undefined properties are lost.
- Functions are lost.
- Symbols are lost.
- Date objects become strings.
- Map objects are not preserved correctly.
- Set objects are not preserved correctly.
- BigInt values cause errors unless transformed.
- Circular references cause errors.
- Special object prototypes are lost.
- NaN and Infinity become null.
const original = { name: 'Aarav', joinedAt: new Date()};
const copy = structuredClone( original );
console.log( copy.joinedAt instanceof Date);Click Run to see what this code prints.
JSON and Local Storage
Browser storage stores string values. To save JavaScript objects or arrays, they are commonly converted to JSON strings first.
JAVASCRIPT OBJECT
{ name: "Aarav", age: 25}
│ ▼
JSON.stringify()
│ ▼
JSON STRING
"{\"name\":\"Aarav\",\"age\":25}"
│ ▼
localStorage
READING DATA
localStorage │ ▼ JSON STRING │ ▼ JSON.parse() │ ▼JAVASCRIPT OBJECTSaving Objects
const user = { name: 'Aarav', age: 25, theme: 'dark'};
localStorage.setItem( 'user', JSON.stringify( user ));Reading Objects
const storedUser = localStorage.getItem( 'user' );
if (storedUser !== null) { const user = JSON.parse( storedUser );
console.log( user.name );}Updating Stored JSON
const storedUser = localStorage.getItem( 'user' );
if (storedUser !== null) { const user = JSON.parse( storedUser );
user.theme = 'light';
localStorage.setItem( 'user', JSON.stringify( user ) );}JSON and APIs
JSON is the most common data format used by modern web APIs. A frontend application can send JSON to a server and receive JSON in response.
FRONTEND APPLICATION
JavaScript Object │ ▼Convert to JSON │ ▼HTTP Request │ ▼
┌─────────────────────┐│ SERVER ││ ││ Parse JSON ││ Process Data ││ Create Response │└──────────┬──────────┘ │ ▼ JSON Response │ ▼ FRONTEND RECEIVES │ ▼ Convert to JavaScript │ ▼ Update InterfaceReceiving JSON Data
{ "id": 101, "name": "Aarav", "role": "student"}The application receives the JSON response and converts it into JavaScript data before using it.
Sending JSON Data
const user = { name: 'Aarav', email: 'aarav@example.com'};
const requestBody = JSON.stringify( user );
console.log( requestBody);HTTP JSON Flow
BROWSER
{ name: "Aarav"}
│ ▼
JSON.stringify()
│ ▼
"{\"name\":\"Aarav\"}"
│ ▼
HTTP REQUEST
Content-Type:application/json
│ ▼
SERVER
Parse JSONProcess Data
│ ▼
HTTP RESPONSE
{ "success": true, "id": 101}
│ ▼
BROWSER
Parse Response
│ ▼
{ success: true, id: 101}Fetch API and JSON
The Fetch API is commonly used to communicate with servers. JSON responses can be converted into JavaScript values using the response.json() method.
Reading JSON Response
async function loadUsers() { try { const response = await fetch( '/api/users' );
if (!response.ok) { throw new Error( 'Request failed' ); }
const users = await response.json();
console.log(users); } catch (error) { console.log( error.message ); }}
loadUsers();- response.json() reads the response body.
- It parses JSON data.
- It returns a Promise.
- The result is a JavaScript value.
- It should normally be awaited in an async function.
Sending JSON with fetch()
async function createUser() { const user = { name: 'Aarav', email: 'aarav@example.com' };
try { const response = await fetch( '/api/users', { method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify( user ) } );
if (!response.ok) { throw new Error( 'Unable to create user' ); }
const result = await response.json();
console.log(result); } catch (error) { console.log( error.message ); }}
createUser();JSON File Structure
JSON data is commonly stored in files using the .json extension.
{ "courses": [ { "id": 1, "title": "HTML", "lessons": 25 }, { "id": 2, "title": "CSS", "lessons": 30 }, { "id": 3, "title": "JavaScript", "lessons": 27 } ]}Loading a JSON File
async function loadCourses() { try { const response = await fetch( '/data/courses.json' );
if (!response.ok) { throw new Error( 'Unable to load courses' ); }
const data = await response.json();
console.log( data.courses ); } catch (error) { console.log( error.message ); }}
loadCourses();JSON Validation
Valid JSON syntax does not guarantee that the data has the structure your application expects. Applications should validate important properties after parsing.
function isValidUser( value) { return ( value !== null && typeof value === 'object' && typeof value.name === 'string' && typeof value.age === 'number' );}
const jsonText = '{"name":"Aarav","age":25}';
const data = JSON.parse( jsonText );
if ( isValidUser(data)) { console.log( 'Valid user data' );} else { console.log( 'Invalid user structure' );}Safe JSON Parsing
function safeParseJSON( jsonText, fallback = null) { try { return JSON.parse( jsonText ); } catch (error) { return fallback; }}
const first = safeParseJSON( '{"name":"Aarav"}' );
const second = safeParseJSON( '{"name":}', {} );
console.log(first);
console.log(second);- JSON.parse() checks JSON syntax.
- It does not verify business rules.
- It does not guarantee required properties exist.
- It does not guarantee values have expected meanings.
- External data should be validated before important use.
Optional Properties
External JSON data may not always contain every property. Optional chaining and nullish coalescing can help safely access optional values.
const user = { name: 'Aarav'};
const city = user.address?.city ?? 'Unknown';
console.log(city);Click Run to see what this code prints.
Destructuring JSON Data
const jsonText = `{ "name": "Aarav", "age": 25, "city": "Mumbai"}`;
const data = JSON.parse( jsonText );
const { name, age, city} = data;
console.log(name);
console.log(age);
console.log(city);Iterating JSON Data
const jsonText = `[ { "id": 1, "name": "Aarav" }, { "id": 2, "name": "Diya" }]`;
const users = JSON.parse( jsonText );
for ( const user of users) { console.log( user.id, user.name );}Filtering JSON Data
const users = [ { name: 'Aarav', active: true }, { name: 'Diya', active: false }, { name: 'Kabir', active: true }];
const activeUsers = users.filter( function (user) { return user.active; } );
console.log( activeUsers);Mapping JSON Data
const users = [ { id: 1, name: 'Aarav' }, { id: 2, name: 'Diya' }];
const names = users.map( function (user) { return user.name; } );
console.log(names);Click Run to see what this code prints.
Searching JSON Data
const courses = [ { id: 1, title: 'HTML' }, { id: 2, title: 'CSS' }, { id: 3, title: 'JavaScript' }];
const course = courses.find( function (item) { return item.id === 3; } );
console.log(course);Sorting JSON Data
const products = [ { name: 'Mouse', price: 800 }, { name: 'Laptop', price: 60000 }, { name: 'Keyboard', price: 2000 }];
products.sort( function (a, b) { return ( a.price - b.price ); });
console.log(products);Complete JSON Example
The following example creates a Course Manager that uses JSON throughout the application. It loads JSON data, converts it into JavaScript objects, renders courses, searches and filters data, adds new courses, saves the updated collection as JSON, and allows the current data to be exported in formatted JSON.
<div class="json-app"> <header class="app-header"> <p class="eyebrow"> JavaScript JSON Project </p>
<h2> Course Data Manager </h2>
<p> Parse, filter, update, store, and export JSON data. </p> </header>
<section class="controls"> <input id="searchInput" type="search" placeholder="Search courses..." >
<select id="levelFilter"> <option value="all"> All Levels </option>
<option value="Beginner"> Beginner </option>
<option value="Intermediate"> Intermediate </option>
<option value="Advanced"> Advanced </option> </select>
<button id="exportButton" type="button" > Show JSON </button> </section>
<section class="stats"> <article> <span> Total Courses </span>
<strong id="totalCourses"> 0 </strong> </article>
<article> <span> Free Courses </span>
<strong id="freeCourses"> 0 </strong> </article>
<article> <span> Total Lessons </span>
<strong id="totalLessons"> 0 </strong> </article> </section>
<section id="courseList" class="course-list" ></section>
<section class="add-course"> <h3> Add Course </h3>
<form id="courseForm"> <input id="titleInput" type="text" placeholder="Course title" required >
<input id="lessonsInput" type="number" placeholder="Lessons" min="1" required >
<select id="courseLevelInput" required > <option value=""> Select Level </option>
<option value="Beginner"> Beginner </option>
<option value="Intermediate"> Intermediate </option>
<option value="Advanced"> Advanced </option> </select>
<label class="checkbox-label"> <input id="freeInput" type="checkbox" >
Free Course </label>
<button type="submit"> Add Course </button> </form> </section>
<section class="json-output"> <div class="output-header"> <h3> JSON Output </h3>
<button id="clearOutputButton" type="button" > Clear </button> </div>
<pre id="jsonOutput">Select "Show JSON" to view data. </pre> </section>
<div id="message" class="message" > Course data ready. </div></div>.json-app { max-width: 1000px; margin: 40px auto; padding: 28px; border-radius: 18px; background: var(--bg-secondary);}
.app-header { margin-bottom: 24px;}
.eyebrow { margin-bottom: 8px; color: var(--accent-light); font-size: 0.8rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em;}
.controls { display: grid; grid-template-columns: 1fr 180px auto; gap: 12px; margin-bottom: 18px;}
.controls input,.controls select,.add-course input,.add-course select { width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; background: var(--bg-primary); color: var(--text-primary);}
.controls button,.add-course button,.output-header button { padding: 12px 16px; border: none; border-radius: 8px; cursor: pointer;}
.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 18px;}
.stats article { padding: 18px; border-radius: 12px; background: var(--bg-primary);}
.stats span,.stats strong { display: block;}
.stats span { margin-bottom: 8px; color: var(--text-secondary); font-size: 0.8rem;}
.stats strong { font-size: 1.5rem;}
.course-list { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px;}
.course-card { padding: 18px; border: 1px solid var(--border-color); border-radius: 12px; background: var(--bg-primary);}
.course-card h3 { margin-bottom: 8px;}
.course-meta { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px;}
.course-meta span { padding: 5px 9px; border-radius: 50px; background: var(--bg-secondary); color: var(--text-secondary); font-size: 0.75rem;}
.add-course,.json-output { margin-top: 18px; padding: 18px; border-radius: 12px; background: var(--bg-primary);}
.add-course form { display: grid; grid-template-columns: 1fr 130px 170px; gap: 10px; margin-top: 14px;}
.checkbox-label { display: flex; align-items: center; gap: 8px;}
.checkbox-label input { width: auto;}
.output-header { display: flex; align-items: center; justify-content: space-between;}
.json-output pre { max-height: 400px; margin-top: 14px; padding: 16px; overflow: auto; border-radius: 10px; background: var(--bg-secondary); white-space: pre-wrap; overflow-wrap: anywhere;}
.message { margin-top: 18px; color: var(--text-secondary);}
@media ( max-width: 750px) { .controls, .stats, .course-list, .add-course form { grid-template-columns: 1fr; }}const initialJSON = `{ "courses": [ { "id": 1, "title": "HTML", "lessons": 25, "level": "Beginner", "free": true }, { "id": 2, "title": "CSS", "lessons": 30, "level": "Beginner", "free": true }, { "id": 3, "title": "JavaScript", "lessons": 27, "level": "Intermediate", "free": true }, { "id": 4, "title": "React", "lessons": 35, "level": "Intermediate", "free": false }, { "id": 5, "title": "Node.js", "lessons": 32, "level": "Advanced", "free": false } ]}`;
const searchInput = document.getElementById( 'searchInput' );
const levelFilter = document.getElementById( 'levelFilter' );
const exportButton = document.getElementById( 'exportButton' );
const totalCourses = document.getElementById( 'totalCourses' );
const freeCourses = document.getElementById( 'freeCourses' );
const totalLessons = document.getElementById( 'totalLessons' );
const courseList = document.getElementById( 'courseList' );
const courseForm = document.getElementById( 'courseForm' );
const titleInput = document.getElementById( 'titleInput' );
const lessonsInput = document.getElementById( 'lessonsInput' );
const courseLevelInput = document.getElementById( 'courseLevelInput' );
const freeInput = document.getElementById( 'freeInput' );
const jsonOutput = document.getElementById( 'jsonOutput' );
const clearOutputButton = document.getElementById( 'clearOutputButton' );
const message = document.getElementById( 'message' );
let courses = [];
function loadInitialData() { try { const parsedData = JSON.parse( initialJSON );
if ( !Array.isArray( parsedData.courses ) ) { throw new Error( 'Invalid course data' ); }
courses = parsedData.courses;
showMessage( 'JSON data parsed successfully.' ); } catch (error) { courses = [];
showMessage( error.message ); }}
function renderCourses() { const searchTerm = searchInput.value .trim() .toLowerCase();
const selectedLevel = levelFilter.value;
const filteredCourses = courses.filter( function (course) { const matchesSearch = course.title .toLowerCase() .includes( searchTerm );
const matchesLevel = selectedLevel === 'all' || course.level === selectedLevel;
return ( matchesSearch && matchesLevel ); } );
courseList.innerHTML = '';
if ( filteredCourses.length === 0 ) { courseList.innerHTML = '<p>No courses found.</p>';
return; }
filteredCourses.forEach( function (course) { const card = document.createElement( 'article' );
card.className = 'course-card';
card.innerHTML = ` <h3> ${course.title} </h3>
<p> Course ID: ${course.id} </p>
<div class="course-meta"> <span> ${course.lessons} Lessons </span>
<span> ${course.level} </span>
<span> ${course.free ? 'Free' : 'Paid'} </span> </div> `;
courseList.appendChild( card ); } );}
function updateStats() { totalCourses.textContent = courses.length;
freeCourses.textContent = courses.filter( function (course) { return course.free; } ).length;
totalLessons.textContent = courses.reduce( function ( total, course ) { return ( total + course.lessons ); }, 0 );}
function showJSON() { const data = { courses: courses };
jsonOutput.textContent = JSON.stringify( data, null, 2 );
showMessage( 'Current data converted to formatted JSON.' );}
function showMessage(text) { message.textContent = text;}
searchInput.addEventListener( 'input', function () { renderCourses(); });
levelFilter.addEventListener( 'change', function () { renderCourses(); });
exportButton.addEventListener( 'click', function () { showJSON(); });
clearOutputButton.addEventListener( 'click', function () { jsonOutput.textContent = 'JSON output cleared.';
showMessage( 'Output cleared.' ); });
courseForm.addEventListener( 'submit', function (event) { event.preventDefault();
const title = titleInput.value .trim();
const lessons = Number( lessonsInput.value );
const level = courseLevelInput.value;
if ( title === '' || !Number.isFinite( lessons ) || lessons < 1 || level === '' ) { showMessage( 'Enter valid course details.' );
return; }
const newCourse = { id: courses.length === 0 ? 1 : Math.max( ...courses.map( function ( course ) { return course.id; } ) ) + 1,
title: title,
lessons: lessons,
level: level,
free: freeInput.checked };
courses.push( newCourse );
courseForm.reset();
renderCourses();
updateStats();
showMessage( `${newCourse.title} added successfully.` ); });
loadInitialData();
renderCourses();
updateStats();Click Run to see what this code prints.
- Creating JSON text.
- Parsing JSON with JSON.parse().
- Handling parsing errors.
- Validating parsed data.
- Working with arrays of objects.
- Searching parsed data.
- Filtering parsed data.
- Rendering JSON data into the DOM.
- Calculating statistics from parsed data.
- Using filter().
- Using reduce().
- Using map().
- Adding new JavaScript objects.
- Updating an in-memory data collection.
- Converting JavaScript data back to JSON.
- Formatting JSON with indentation.
- Displaying JSON output.
- Combining JSON, DOM, events, arrays, objects, and functions.
JSON Processing Flow
EXTERNAL DATA SOURCE
APIFileBrowser StorageServer
│ ▼
JSON TEXT
│ ▼
JSON.parse()
│ ▼
JAVASCRIPT DATA
ObjectArrayStringNumberBooleannull
│ ▼
APPLICATION PROCESSING
ReadValidateFilterMapSearchSortUpdateDisplay
│ ▼
JAVASCRIPT DATA
│ ▼
JSON.stringify()
│ ▼
JSON TEXT
│ ▼
Send to APIStore in BrowserSave in FileTransfer to SystemReal-World Applications
REST APIs
Send and receive structured data between frontend and backend systems.
Browser Storage
Store objects and arrays as JSON strings.
Configuration Files
Define application and tool settings.
E-Commerce
Represent products, carts, orders, and customer data.
User Profiles
Exchange account, preference, and profile information.
Course Platforms
Represent courses, lessons, progress, and curriculum data.
Mobile Applications
Exchange data between mobile clients and servers.
Dashboards
Load and process analytics data from APIs.
Games
Store settings, progress, levels, and game state.
Forms
Send structured form data to backend services.
Application State
Serialize compatible application state for storage or transfer.
Microservices
Exchange structured information between independent services.
Common Beginner Mistakes
- Thinking JSON and JavaScript objects are the same thing.
- Forgetting that JSON is text.
- Using single quotes in strict JSON.
- Leaving property names unquoted.
- Using trailing commas.
- Adding comments inside JSON.
- Trying to store undefined in JSON.
- Trying to store functions in JSON.
- Trying to store symbols in JSON.
- Expecting JSON to support every JavaScript value.
- Using NaN and expecting it to remain NaN.
- Using Infinity and expecting it to remain Infinity.
- Trying to stringify BigInt directly.
- Forgetting that JSON.stringify() returns a string.
- Forgetting that JSON.parse() expects valid JSON text.
- Calling JSON.parse() on an existing JavaScript object.
- Calling JSON.stringify() when parsing is required.
- Calling JSON.parse() when serialization is required.
- Ignoring JSON.parse() errors.
- Parsing external data without try...catch when failure is possible.
- Assuming valid JSON syntax means valid application data.
- Failing to validate required properties.
- Assuming every API response contains the expected structure.
- Accessing deeply nested properties without checking their existence.
- Forgetting that JSON has no Date data type.
- Expecting parsed date strings to become Date objects automatically.
- Forgetting to use a reviver or manual Date conversion.
- Removing values accidentally with a reviver.
- Forgetting to return values from a reviver.
- Removing properties accidentally with a replacer.
- Forgetting to return values from a replacer.
- Assuming undefined object properties become null.
- Forgetting that undefined object properties are omitted.
- Forgetting that undefined array elements become null.
- Expecting functions to survive serialization.
- Expecting symbols to survive serialization.
- Using JSON deep copy for Date objects.
- Using JSON deep copy for Map objects.
- Using JSON deep copy for Set objects.
- Using JSON deep copy with circular references.
- Using JSON deep copy with BigInt values.
- Ignoring structuredClone() when it better fits the copying requirement.
- Creating circular references and trying to stringify them.
- Saving objects directly to localStorage.
- Forgetting that localStorage stores strings.
- Forgetting to stringify before storing objects.
- Forgetting to parse stored JSON after reading it.
- Parsing null from localStorage without checking the result.
- Assuming stored JSON is always valid.
- Forgetting to update browser storage after changing parsed data.
- Sending a JavaScript object as a JSON request body without serialization when the API expects JSON text.
- Forgetting the application/json Content-Type header.
- Calling response.json() without awaiting it.
- Assuming response.json() returns data immediately.
- Ignoring failed HTTP responses.
- Assuming fetch() rejects for every HTTP error status.
- Failing to check response.ok.
- Using eval() to parse JSON.
- Trusting external data without validation.
- Putting passwords or secrets into JSON responses unnecessarily.
- Logging sensitive JSON data.
- Displaying untrusted JSON content with innerHTML.
- Manually constructing complex JSON strings.
- Forgetting to escape quotes inside manually created JSON strings.
- Using very large deeply nested JSON without considering performance.
- Mutating arrays while sorting when a copy was expected.
- Assuming parsed JSON objects have custom class methods.
- Expecting prototypes to survive JSON serialization.
- Assuming property order should be used as application logic.
- Confusing missing properties with properties containing null.
- Treating null and undefined as identical.
- Forgetting that JSON property names are strings.
- Using comments in .json files.
- Not testing invalid JSON.
- Not testing missing properties.
- Not testing null values.
- Not testing empty arrays.
- Not testing empty objects.
- Not testing failed API responses.
// ❌ JavaScript object is not JSON textconst user = { name: 'Aarav'};
JSON.parse(user);
// ✅ Parse JSON textconst jsonText = '{"name":"Aarav"}';
const parsed = JSON.parse( jsonText );
// ❌ stringify returns a stringconst result = JSON.stringify( user );
console.log( result.name);
// ✅ Parse again if object access is neededconst restored = JSON.parse( result );
console.log( restored.name);
// ❌ Invalid strict JSONconst invalid = `{ name: 'Aarav',}`;
// ✅ Valid JSONconst valid = `{ "name": "Aarav"}`;
// ❌ Save object directlylocalStorage.setItem( 'user', user);
// ✅ Convert object to JSONlocalStorage.setItem( 'user', JSON.stringify( user ));
// ❌ Assume API response succeededconst response = await fetch( '/api/users' );
const data = await response.json();
// ✅ Check HTTP responseconst safeResponse = await fetch( '/api/users' );
if (!safeResponse.ok) { throw new Error( 'Request failed' );}
const safeData = await safeResponse.json();Best Practices
- Remember that JSON is a text format.
- Understand the difference between JSON and JavaScript objects.
- Use double quotes for JSON property names.
- Use double quotes for JSON string values.
- Do not use comments in strict JSON.
- Do not use trailing commas in JSON.
- Use JSON.parse() to convert JSON text into JavaScript values.
- Use JSON.stringify() to convert JavaScript values into JSON text.
- Handle JSON.parse() failures when data may be invalid.
- Use try...catch for untrusted or external JSON text.
- Validate important data after parsing.
- Do not assume syntax validation guarantees correct application data.
- Check required properties.
- Check expected data types.
- Handle optional properties safely.
- Use optional chaining for deeply nested optional data.
- Use nullish coalescing for appropriate fallback values.
- Use revivers only when parsing transformations are genuinely useful.
- Return unchanged values from revivers when no transformation is required.
- Use replacers to remove or transform serializable properties when appropriate.
- Never depend on serialization alone as a security system.
- Remove sensitive data before sending or storing JSON.
- Use the third JSON.stringify() argument for human-readable output.
- Use compact JSON for normal network transfer unless readability is required.
- Understand how undefined behaves during serialization.
- Understand how functions behave during serialization.
- Understand how symbols behave during serialization.
- Handle NaN and Infinity intentionally.
- Convert BigInt values intentionally before serialization.
- Remember that Date objects become strings.
- Restore dates explicitly when Date behavior is required.
- Avoid circular references in data intended for JSON serialization.
- Do not use JSON deep copy blindly.
- Prefer structuredClone() when it better matches the copying requirement.
- Use JSON.stringify() before storing objects in localStorage.
- Use JSON.parse() after reading stored object data.
- Check for null when reading missing storage values.
- Handle corrupted stored JSON safely.
- Use application/json when sending JSON HTTP requests.
- Use JSON.stringify() for JSON request bodies.
- Await response.json().
- Check response.ok for HTTP failures.
- Handle network errors.
- Validate API response structures.
- Never use eval() to parse JSON.
- Treat external JSON as untrusted input.
- Avoid rendering untrusted values directly through innerHTML.
- Use textContent when displaying plain external text.
- Keep JSON structures understandable.
- Avoid unnecessary deeply nested data.
- Use arrays for ordered collections.
- Use objects for named properties.
- Use null intentionally to represent missing values.
- Distinguish missing properties from null values.
- Use array methods to process parsed collections.
- Use filter() for selecting data.
- Use map() for transforming data.
- Use find() for locating one item.
- Use sort() carefully because it mutates the array.
- Test empty arrays.
- Test empty objects.
- Test null values.
- Test missing properties.
- Test invalid JSON.
- Test malformed API responses.
- Test failed network requests.
- Keep sensitive information out of JSON whenever it is not required.
Frequently Asked Questions
JSON stands for JavaScript Object Notation.
No. JSON is a text-based data format.
No. JSON is text, while a JavaScript object is a JavaScript value.
It is lightweight, readable, language-independent, and easy for applications to process.
JSON supports strings, numbers, booleans, null, objects, and arrays.
No.
No.
No.
No. Dates are normally represented as strings.
Strict JSON does not support comments.
No. JSON strings and property names require double quotes.
No.
It converts valid JSON text into a JavaScript value.
It throws a SyntaxError.
Use try...catch when parsing data that may be invalid.
It is an optional function used by JSON.parse() to transform parsed values.
Yes. It can convert selected date strings into Date objects.
It converts a JavaScript value into JSON text.
It returns a string.
It is an optional function that transforms or removes values during serialization.
It selects which property names should be included in serialized output.
Pass an indentation value as the third argument to JSON.stringify().
They are omitted during JSON serialization.
They are converted to null.
Function-valued properties are omitted during serialization.
It is converted to null.
It is converted to null.
No. Standard JSON.stringify() normally throws a TypeError for BigInt.
Convert it to a string or another supported representation.
They are normally converted into ISO-formatted strings.
It is a method an object can define to control its JSON serialization result.
It occurs when an object eventually refers back to itself.
Not directly. It normally throws a TypeError.
It can copy simple JSON-compatible data, but it loses unsupported values and special object types.
structuredClone() is often more appropriate when supported and compatible with the data.
Because localStorage stores strings, so objects and arrays are commonly serialized first.
Use JSON.stringify() before passing the value to localStorage.setItem().
Read the string with localStorage.getItem() and parse it with JSON.parse().
It reads a response body and parses it as JSON.
No. It returns a Promise.
Stringify the request body and usually set Content-Type to application/json.
No. It validates JSON syntax, not your business requirements.
No. Important external data should be validated before use.
No. JSON.parse() is the correct and safer method for parsing JSON.
Yes. Once a JSON array is parsed, it becomes a normal JavaScript array.
Yes. Use array methods such as filter().
Yes. Use methods such as map().
Yes. Use methods such as find() or findIndex().
Yes. Parsed arrays can be sorted using sort().
Key Takeaways
- JSON stands for JavaScript Object Notation.
- JSON is a text-based data format.
- JSON is not the same as a JavaScript object.
- JSON is commonly used for data exchange.
- JSON property names require double quotes.
- JSON string values require double quotes.
- JSON does not support comments.
- JSON does not support trailing commas.
- JSON supports strings.
- JSON supports numbers.
- JSON supports booleans.
- JSON supports null.
- JSON supports objects.
- JSON supports arrays.
- JSON can represent nested structures.
- JSON.parse() converts JSON text into JavaScript values.
- Invalid JSON causes JSON.parse() to throw an error.
- try...catch can safely handle parsing failures.
- A reviver can transform parsed values.
- Date strings can be restored with a reviver.
- JSON.stringify() converts JavaScript values into JSON text.
- A replacer function can transform or remove values.
- A replacer array can select properties.
- The space argument formats JSON output.
- undefined object properties are omitted.
- undefined array elements become null.
- Functions are not represented in JSON.
- Symbols are not represented in JSON.
- NaN becomes null during serialization.
- Infinity becomes null during serialization.
- BigInt cannot be serialized directly.
- Date objects become strings.
- toJSON() can customize serialization.
- Circular references cannot be serialized directly.
- JSON-based deep copying has important limitations.
- structuredClone() is often better for compatible complex values.
- Browser storage commonly uses JSON strings for objects.
- JSON is widely used by web APIs.
- response.json() parses JSON response data.
- JSON request bodies are commonly created with JSON.stringify().
- application/json identifies JSON HTTP content.
- Valid JSON syntax does not guarantee valid application data.
- External data should be validated.
- Optional properties should be accessed safely.
- Parsed arrays can use normal JavaScript array methods.
- JSON is essential for modern frontend and backend communication.
Summary
JSON is one of the most important data formats in modern software development. It provides a lightweight and language-independent way to represent structured information using objects, arrays, strings, numbers, booleans, and null.
Although JSON syntax resembles JavaScript object syntax, JSON is text. JavaScript objects must be converted into JSON strings before they can be stored or transmitted as JSON, and JSON text must be parsed before JavaScript can work with it as normal objects and arrays.
JSON.parse() converts valid JSON text into JavaScript values. Invalid JSON causes an error, so external or uncertain JSON data should be parsed carefully. The optional reviver function can transform values during parsing and can be used to restore values such as dates.
JSON.stringify() converts JavaScript values into JSON text. Replacer functions and replacer arrays can control which values are included, while the space argument creates readable formatted output.
JSON supports fewer data types than JavaScript. Values such as undefined, functions, symbols, BigInt, Date objects, NaN, Infinity, and circular references require special understanding and sometimes custom handling.
JSON is commonly used with browser storage, files, APIs, and HTTP requests. Objects are stringified before storage or transmission and parsed after they are received or retrieved.
Parsed JSON data becomes normal JavaScript data. You can access properties, destructure objects, iterate arrays, filter collections, map values, search records, sort results, update information, and render data into the DOM.
Mastering JSON gives you the foundation required for API communication, browser storage, server interaction, configuration management, and data-driven web applications.
- You understand what JSON is.
- You understand why JSON is used.
- You understand the difference between JSON and JavaScript objects.
- You understand JSON syntax rules.
- You know every JSON data type.
- You can create JSON strings.
- You can create JSON numbers.
- You can use JSON booleans.
- You can use null in JSON.
- You can create JSON objects.
- You can create JSON arrays.
- You can create nested JSON structures.
- You can identify valid and invalid JSON.
- You can use JSON.parse().
- You can parse JSON objects.
- You can parse JSON arrays.
- You can access parsed data.
- You can handle parsing errors.
- You understand the JSON parsing flow.
- You can use a reviver.
- You can restore date strings.
- You can transform values during parsing.
- You can use JSON.stringify().
- You can stringify objects.
- You can stringify arrays.
- You can stringify nested data.
- You can use replacer functions.
- You can use replacer arrays.
- You can format JSON output.
- You understand the space argument.
- You understand unsupported values.
- You understand how undefined behaves.
- You understand how functions behave.
- You understand how symbols behave.
- You understand how NaN and Infinity behave.
- You understand BigInt serialization.
- You understand Date serialization.
- You understand toJSON().
- You understand circular references.
- You understand JSON-based deep copying.
- You understand its limitations.
- You can use JSON with browser storage.
- You can save objects as JSON.
- You can read stored JSON.
- You can update stored JSON.
- You understand JSON API communication.
- You can receive JSON data.
- You can send JSON data.
- You understand HTTP JSON flow.
- You can use fetch() with JSON.
- You can read JSON responses.
- You can send JSON request bodies.
- You can create JSON files.
- You can load JSON files.
- You understand JSON validation.
- You can safely parse uncertain JSON.
- You can handle optional properties.
- You can destructure parsed data.
- You can iterate through parsed data.
- You can filter JSON data.
- You can map JSON data.
- You can search JSON data.
- You can sort JSON data.
- You can build a complete JSON-based application.
- You are ready to learn Local Storage.