LearnContact
Lesson 2460 min read

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 You Will Learn
  • 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.

user.json
{
    "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.

Important Definition
  • 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.

JSON Communication Analogy
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 Information

JSON vs JavaScript Object

JSON and JavaScript objects may look similar, but they are not the same.

JavaScript Object
const user = {
    name: 'Aarav',
    age: 25,
    isStudent: false
};


console.log(
    typeof user
);
Output
JSON String
const jsonText = `{
    "name": "Aarav",
    "age": 25,
    "isStudent": false
}`;


console.log(
    typeof jsonText
);
Output
JSON and Object Comparison
JAVASCRIPT OBJECT

{
    name: 'Aarav',
    age: 25
}

Type:
object

Keys:
Quotes usually optional

Strings:
Single or double quotes allowed

Can Contain:
Functions
undefined
Symbols
Other JavaScript values


JSON

{
    "name": "Aarav",
    "age": 25
}

Type:
Text / string

Keys:
Double quotes required

Strings:
Double quotes required

Can Contain:
Object
Array
String
Number
Boolean
null

JSON 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.
Valid JSON
{
    "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.

All JSON Data Types
{
    "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.

JSON String Values
{
    "name": "JavaScript",
    "message": "Hello, World!",
    "country": "India"
}
String Rules
VALID

"JavaScript"


INVALID JSON

'JavaScript'


VALID

{
    "name": "Aarav"
}


INVALID JSON

{
    'name': 'Aarav'
}

Special characters inside JSON strings must be escaped when necessary.

Escaped JSON String
{
    "message": "He said, \"Hello!\"",
    "path": "C:\\Users\\Student",
    "text": "Line 1\nLine 2"
}

JSON Numbers

JSON supports numeric values without quotes.

JSON Numbers
{
    "age": 25,
    "price": 499.99,
    "temperature": -5,
    "population": 1400000000
}
Number Rules
  • 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

JSON Boolean Values
{
    "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.

JSON null
{
    "middleName": null,
    "profileImage": null
}

JSON Objects

A JSON object is enclosed in curly braces and contains key-value pairs.

JSON Object
{
    "name": "Aarav",
    "age": 25,
    "city": "Mumbai"
}
JSON Object Structure
{
    "name": "Aarav",
    "age": 25
}
    │       │
    │       └── Value
    │
    └── Key


KEY-VALUE PAIR

"name": "Aarav"
   │        │
   │        └── Value
   │
   └── Property Name

JSON Arrays

A JSON array is an ordered collection of values enclosed in square brackets.

JSON Array
[
    "HTML",
    "CSS",
    "JavaScript"
]
Array of Objects
[
    {
        "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.

Nested JSON
{
    "name": "Aarav",
    "address": {
        "city": "Mumbai",
        "state": "Maharashtra",
        "country": "India"
    },
    "skills": [
        "HTML",
        "CSS",
        "JavaScript"
    ]
}

Complex JSON Structure

Course Data
{
    "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
    }
}
Nested Structure
ROOT OBJECT
     │
     ▼
   course
     │
     ├── id
     ├── title
     ├── free
     │
     ├── instructor
     │      │
     │      ├── name
     │      └── experience
     │
     ├── topics
     │      │
     │      ├── Topic Object
     │      ├── Topic Object
     │      └── Topic Object
     │
     ├── rating
     └── certificate

Valid and Invalid JSON

Valid JSON
{
    "name": "Aarav",
    "age": 25
}
Invalid JSON - Unquoted Key
{
    name: "Aarav"
}
Invalid JSON - Single Quotes
{
    'name': 'Aarav'
}
Invalid JSON - Trailing Comma
{
    "name": "Aarav",
    "age": 25,
}
Invalid JSON - Comment
{
    // User name
    "name": "Aarav"
}
Strict JSON Syntax
  • 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.

Parse JSON
const jsonText =
    '{"name":"Aarav","age":25}';


const user =
    JSON.parse(
        jsonText
    );


console.log(user);

console.log(
    typeof user
);
Output

Parsing JSON Objects

Parse Object JSON
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
);
Output

Parsing JSON Arrays

Parse Array JSON
const jsonText =
    '["HTML","CSS","JavaScript"]';


const skills =
    JSON.parse(
        jsonText
    );


console.log(
    skills[0]
);

console.log(
    skills.length
);
Output

Accessing Parsed Data

Access Nested 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]
);
Output

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.

Invalid JSON
const jsonText =
    '{"name":"Aarav",}';


const user =
    JSON.parse(
        jsonText
    );
Result
Safe Parsing with try...catch
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.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.

Reviver Function
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.

Restore Date Object
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
);
Output

Transforming Values During Parsing

Transform Parsed Values
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);
Output

JSON.stringify()

The JSON.stringify() method converts a JavaScript value into JSON text.

Convert Object to JSON
const user = {
    name: 'Aarav',
    age: 25,
    active: true
};


const jsonText =
    JSON.stringify(
        user
    );


console.log(jsonText);

console.log(
    typeof jsonText
);
Output

Stringifying Objects

Object to JSON
const course = {
    title: 'Core JavaScript',
    lessons: 27,
    free: true
};


const json =
    JSON.stringify(
        course
    );


console.log(json);
Output

Stringifying Arrays

Array to JSON
const skills = [
    'HTML',
    'CSS',
    'JavaScript'
];


const json =
    JSON.stringify(
        skills
    );


console.log(json);
Output

Stringifying Nested Data

Nested Object to JSON
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.

Replacer Function
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);
Output
Transform Values
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.

Select Properties
const user = {
    id: 101,
    name: 'Aarav',
    age: 25,
    password: 'secret123',
    role: 'student'
};


const json =
    JSON.stringify(
        user,
        [
            'id',
            'name',
            'role'
        ]
    );


console.log(json);
Output

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.

Pretty Printed JSON
const user = {
    name: 'Aarav',
    age: 25,
    skills: [
        'JavaScript',
        'React'
    ]
};


const json =
    JSON.stringify(
        user,
        null,
        2
    );


console.log(json);
Output

The space Argument

Different Formatting Options
JSON.stringify(
    data,
    null,
    2
);


JSON.stringify(
    data,
    null,
    4
);


JSON.stringify(
    data,
    null,
    '\t'
);
JSON.stringify Arguments
JSON.stringify(
    value,
    replacer,
    space
);


value

The JavaScript value
to serialize.


replacer

Optional transformation
or property selection.


space

Optional indentation
for readable output.

JSON Stringify Flow

JSON.stringify() Flow
JAVASCRIPT VALUE

{
    name: "Aarav",
    age: 25
}

             │
             ▼

       JSON.stringify()

             │
             ▼

          JSON TEXT

"{\"name\":\"Aarav\",\"age\":25}"

             │
             ▼

Can Be:

Sent to API
Stored in Browser
Saved in File
Transferred to Another System

Unsupported 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

undefined in Object
const user = {
    name: 'Aarav',
    age: undefined
};


console.log(
    JSON.stringify(
        user
    )
);
Output

Object properties containing undefined are omitted.

undefined in Array
const values = [
    10,
    undefined,
    30
];


console.log(
    JSON.stringify(
        values
    )
);
Output

Functions in JSON

Function Property
const user = {
    name: 'Aarav',

    greet: function () {
        return 'Hello';
    }
};


console.log(
    JSON.stringify(
        user
    )
);
Output

Functions are not part of the JSON data model and object properties containing functions are omitted during serialization.

Symbols in JSON

Symbol Property
const id =
    Symbol('id');


const user = {
    name: 'Aarav',
    code: id
};


console.log(
    JSON.stringify(
        user
    )
);
Output

NaN and Infinity

Special Number Values
const values = {
    first: NaN,
    second: Infinity,
    third: -Infinity
};


console.log(
    JSON.stringify(
        values
    )
);
Output

BigInt and JSON

JSON.stringify() cannot directly serialize a BigInt value and normally throws a TypeError.

BigInt Serialization Error
const data = {
    value: 12345678901234567890n
};


JSON.stringify(
    data
);
Result
Convert BigInt to String
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.

Serialize Date
const event = {
    title: 'JavaScript Class',
    date: new Date(
        '2026-07-09T10:30:00Z'
    )
};


const json =
    JSON.stringify(
        event
    );


console.log(json);
Output
Date Conversion
  • 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.

Custom toJSON Method
const user = {
    id: 101,
    name: 'Aarav',
    password: 'secret123',

    toJSON() {
        return {
            id: this.id,
            name: this.name
        };
    }
};


console.log(
    JSON.stringify(
        user
    )
);
Output

Circular References

A circular reference occurs when an object eventually refers back to itself. Standard JSON serialization cannot represent circular references.

Circular Reference
const user = {
    name: 'Aarav'
};


user.self = user;


JSON.stringify(
    user
);
Result
Circular Reference
user
 │
 ├── name
 │
 └── self
      │
      └──────────────┐
                     │
                     ▼
                   user

Infinite Reference Loop

Deep Copy with JSON

A common historical technique for copying simple JSON-compatible data is to stringify the value and then parse the result.

JSON Deep Copy
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
);
Output

Limitations of JSON Deep Copy

JSON Copy Is Not Suitable for Every Value
  • 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.
Prefer structuredClone for Supported Data
const original = {
    name: 'Aarav',
    joinedAt:
        new Date()
};


const copy =
    structuredClone(
        original
    );


console.log(
    copy.joinedAt
        instanceof Date
);
Output

JSON and Local Storage

Browser storage stores string values. To save JavaScript objects or arrays, they are commonly converted to JSON strings first.

Storage Conversion Flow
JAVASCRIPT OBJECT

{
    name: "Aarav",
    age: 25
}

       │
       ▼

 JSON.stringify()

       │
       ▼

JSON STRING

"{\"name\":\"Aarav\",\"age\":25}"

       │
       ▼

 localStorage


READING DATA

 localStorage
       │
       ▼
  JSON STRING
       │
       ▼
   JSON.parse()
       │
       ▼
JAVASCRIPT OBJECT

Saving Objects

Save Object
const user = {
    name: 'Aarav',
    age: 25,
    theme: 'dark'
};


localStorage.setItem(
    'user',
    JSON.stringify(
        user
    )
);

Reading Objects

Read Stored Object
const storedUser =
    localStorage.getItem(
        'user'
    );


if (storedUser !== null) {
    const user =
        JSON.parse(
            storedUser
        );

    console.log(
        user.name
    );
}

Updating Stored JSON

Update Stored Object
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.

API Communication
FRONTEND APPLICATION

JavaScript Object
       │
       ▼
Convert to JSON
       │
       ▼
HTTP Request
       │
       ▼

┌─────────────────────┐
│       SERVER        │
│                     │
│ Parse JSON          │
│ Process Data        │
│ Create Response     │
└──────────┬──────────┘
           │
           ▼
       JSON Response
           │
           ▼
     FRONTEND RECEIVES
           │
           ▼
   Convert to JavaScript
           │
           ▼
      Update Interface

Receiving JSON Data

Server Response
{
    "id": 101,
    "name": "Aarav",
    "role": "student"
}

The application receives the JSON response and converts it into JavaScript data before using it.

Sending JSON Data

Prepare Data
const user = {
    name: 'Aarav',
    email: 'aarav@example.com'
};


const requestBody =
    JSON.stringify(
        user
    );


console.log(
    requestBody
);

HTTP JSON Flow

Request and Response Flow
BROWSER

{
    name: "Aarav"
}

       │
       ▼

JSON.stringify()

       │
       ▼

"{\"name\":\"Aarav\"}"

       │
       ▼

HTTP REQUEST

Content-Type:
application/json

       │
       ▼

SERVER

Parse JSON
Process 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

Fetch JSON Data
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()
  • 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()

POST JSON Data
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.json
{
    "courses": [
        {
            "id": 1,
            "title": "HTML",
            "lessons": 25
        },
        {
            "id": 2,
            "title": "CSS",
            "lessons": 30
        },
        {
            "id": 3,
            "title": "JavaScript",
            "lessons": 27
        }
    ]
}

Loading a JSON File

Load 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.

Validate Parsed Data
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

Reusable Safe Parser
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);
Parsing Is Not Full Validation
  • 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.

Safe Property Access
const user = {
    name: 'Aarav'
};


const city =
    user.address?.city
    ?? 'Unknown';


console.log(city);
Output

Destructuring JSON Data

Destructure Parsed 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

Loop Through Parsed Array
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

Filter Parsed 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

Transform Parsed Data
const users = [
    {
        id: 1,
        name: 'Aarav'
    },
    {
        id: 2,
        name: 'Diya'
    }
];


const names =
    users.map(
        function (user) {
            return user.name;
        }
    );


console.log(names);
Output

Searching JSON Data

Find Object
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

Sort Parsed 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.

index.html
<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>
style.css
.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;
    }
}
script.js
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();
Browser Output
What This Example Demonstrates
  • 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

Complete JSON Flow
EXTERNAL DATA SOURCE

API
File
Browser Storage
Server

        │
        ▼

     JSON TEXT

        │
        ▼

   JSON.parse()

        │
        ▼

JAVASCRIPT DATA

Object
Array
String
Number
Boolean
null

        │
        ▼

APPLICATION PROCESSING

Read
Validate
Filter
Map
Search
Sort
Update
Display

        │
        ▼

JAVASCRIPT DATA

        │
        ▼

 JSON.stringify()

        │
        ▼

     JSON TEXT

        │
        ▼

Send to API
Store in Browser
Save in File
Transfer to System

Real-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

Avoid These 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.
Common JSON Mistakes
// ❌ JavaScript object is not JSON text
const user = {
    name: 'Aarav'
};

JSON.parse(user);


// ✅ Parse JSON text
const jsonText =
    '{"name":"Aarav"}';

const parsed =
    JSON.parse(
        jsonText
    );


// ❌ stringify returns a string
const result =
    JSON.stringify(
        user
    );

console.log(
    result.name
);


// ✅ Parse again if object access is needed
const restored =
    JSON.parse(
        result
    );

console.log(
    restored.name
);


// ❌ Invalid strict JSON
const invalid = `
{
    name: 'Aarav',
}
`;


// ✅ Valid JSON
const valid = `
{
    "name": "Aarav"
}
`;


// ❌ Save object directly
localStorage.setItem(
    'user',
    user
);


// ✅ Convert object to JSON
localStorage.setItem(
    'user',
    JSON.stringify(
        user
    )
);


// ❌ Assume API response succeeded
const response =
    await fetch(
        '/api/users'
    );

const data =
    await response.json();


// ✅ Check HTTP response
const 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

What does JSON stand for?

JSON stands for JavaScript Object Notation.

Is JSON a programming language?

No. JSON is a text-based data format.

Is JSON the same as a JavaScript object?

No. JSON is text, while a JavaScript object is a JavaScript value.

Why is JSON widely used?

It is lightweight, readable, language-independent, and easy for applications to process.

Which data types does JSON support?

JSON supports strings, numbers, booleans, null, objects, and arrays.

Does JSON support undefined?

No.

Does JSON support functions?

No.

Does JSON support symbols?

No.

Does JSON support Date objects?

No. Dates are normally represented as strings.

Can JSON contain comments?

Strict JSON does not support comments.

Can JSON use single quotes?

No. JSON strings and property names require double quotes.

Can JSON contain trailing commas?

No.

What does JSON.parse() do?

It converts valid JSON text into a JavaScript value.

What happens when JSON.parse() receives invalid JSON?

It throws a SyntaxError.

How should invalid JSON be handled?

Use try...catch when parsing data that may be invalid.

What is a JSON reviver?

It is an optional function used by JSON.parse() to transform parsed values.

Can a reviver restore Date objects?

Yes. It can convert selected date strings into Date objects.

What does JSON.stringify() do?

It converts a JavaScript value into JSON text.

What type does JSON.stringify() return?

It returns a string.

What is a replacer function?

It is an optional function that transforms or removes values during serialization.

What is a replacer array?

It selects which property names should be included in serialized output.

How do I format JSON output?

Pass an indentation value as the third argument to JSON.stringify().

What happens to undefined object properties?

They are omitted during JSON serialization.

What happens to undefined array elements?

They are converted to null.

What happens to functions in objects?

Function-valued properties are omitted during serialization.

What happens to NaN in JSON.stringify()?

It is converted to null.

What happens to Infinity?

It is converted to null.

Can BigInt be stringified directly?

No. Standard JSON.stringify() normally throws a TypeError for BigInt.

How can BigInt be stored in JSON?

Convert it to a string or another supported representation.

What happens to Date objects?

They are normally converted into ISO-formatted strings.

What is toJSON()?

It is a method an object can define to control its JSON serialization result.

What is a circular reference?

It occurs when an object eventually refers back to itself.

Can JSON.stringify() handle circular references?

Not directly. It normally throws a TypeError.

Can JSON be used for deep copying?

It can copy simple JSON-compatible data, but it loses unsupported values and special object types.

What is better than JSON deep copying for many JavaScript values?

structuredClone() is often more appropriate when supported and compatible with the data.

Why use JSON with localStorage?

Because localStorage stores strings, so objects and arrays are commonly serialized first.

How do I save an object in localStorage?

Use JSON.stringify() before passing the value to localStorage.setItem().

How do I read a stored object?

Read the string with localStorage.getItem() and parse it with JSON.parse().

What does response.json() do?

It reads a response body and parses it as JSON.

Does response.json() return data immediately?

No. It returns a Promise.

How do I send JSON with fetch()?

Stringify the request body and usually set Content-Type to application/json.

Does JSON.parse() validate application rules?

No. It validates JSON syntax, not your business requirements.

Should external JSON be trusted automatically?

No. Important external data should be validated before use.

Can I use eval() instead of JSON.parse()?

No. JSON.parse() is the correct and safer method for parsing JSON.

Can parsed JSON data use array methods?

Yes. Once a JSON array is parsed, it becomes a normal JavaScript array.

Can I filter parsed JSON data?

Yes. Use array methods such as filter().

Can I transform parsed JSON data?

Yes. Use methods such as map().

Can I search parsed JSON data?

Yes. Use methods such as find() or findIndex().

Can I sort parsed JSON data?

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.

Lesson 24 Completed
  • 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.
Next Lesson →

JavaScript Local Storage