JSON Handling

  • Learn how to convert objects to JSON and JSON to objects using parse and stringify.
  • Introduction to JSON Handling

    Modern web applications constantly exchange data between:

    • Browser and server

    • Frontend and backend

    • APIs and databases

    • Browser storage (localStorage / sessionStorage)

    This data is usually exchanged in a standard text format called JSON.

    Understanding JSON handling is mandatory for:

    • API integration

    • Browser storage

    • AJAX / Fetch

    • Real-world JavaScript applications

    What is JSON ?

    JSON stands for JavaScript Object Notation.

    JSON is a lightweight, text-based data format used for storing and transporting data.

    Simple Definition

    JSON is a string format that represents data in key–value pairs, similar to JavaScript objects.

    Why JSON Is Used

    JSON is popular because it is:

    • Easy to read

    • Easy to write

    • Language-independent

    • Lightweight

    • Fast for data transfer

    JSON vs JavaScript Object

    Although JSON looks like a JavaScript object, they are not the same.

    JavaScript Object

    let user = {

      name: "Amit",

      age: 25,

      isAdmin: true

    };

    JSON Format

    {

      "name": "Amit",

      "age": 25,

      "isAdmin": true

    }

    Key Differences

    JavaScript Object

    JSON

    Can store functions

    Cannot store functions

    Keys can be without quotes

    Keys must be in double quotes

    Used in code

    Used for data exchange

    Not a string

    Always a string

    Where JSON Is Used

    JSON is used in:

    • API responses

    • Sending data to servers

    • Fetch and AJAX

    • localStorage and sessionStorage

    • Configuration files

    • Database communication

    JSON Data Types Supported

    JSON supports only the following data types:

    • String

    • Number

    • Boolean

    • Object

    • Array

    • null

    JSON does not support:

    • Functions

    • Dates (directly)

    • Undefined

    JSON Handling in JavaScript

    JavaScript provides a built-in JSON object to handle JSON data.

    Main methods:

    1. JSON.stringify()

    2. JSON.parse()

    JSON.stringify()

    What It Does

    Converts a JavaScript object into a JSON string.

    Syntax

    JSON.stringify(value)

Object to JSON Example

Converts a JavaScript object into a JSON string using JSON.stringify().

let user = {
  name: "Ravi",
  age: 30,
  city: "Delhi"
};

let jsonData = JSON.stringify(user);
console.log(jsonData);
  • Now this data can be:

    • Sent to a server

    • Stored in browser storage

    Why JSON.stringify() Is Important

    Browser storage can store only strings.

    So before saving an object:

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

    JSON.parse()

    What It Does

    Converts a JSON string back into a JavaScript object.

    Syntax

    JSON.parse(jsonString)

JSON to Object Example

Converts a JSON string into a JavaScript object using JSON.parse().

let jsonData = '{"name":"Ravi","age":30}';

let userObj = JSON.parse(jsonData);
console.log(userObj.name);
  • JSON Handling with Browser Storage

    Storing JSON in localStorage

Store Object in LocalStorage Example

Converts an object into JSON format and stores it in localStorage.

let student = {
  name: "Neha",
  marks: 85
};

localStorage.setItem("studentData", JSON.stringify(student));

Retrieve Object from LocalStorage Example

Gets JSON data from localStorage and converts it back into an object.

Retrieving JSON from localStorage
let data = localStorage.getItem("studentData");
let studentObj = JSON.parse(data);

console.log(studentObj.marks);
  • JSON Handling with Arrays

Array to JSON Example

Converts an array of objects into a JSON string.

let users = [
  { name: "Amit", age: 22 },
  { name: "Pooja", age: 24 }
];

let jsonUsers = JSON.stringify(users);
console.log(jsonUsers);
  • Parsing JSON Array

    let parsedUsers = JSON.parse(jsonUsers);

    console.log(parsedUsers[0].name);

    Common JSON Handling Errors

    Error 1: Parsing Invalid JSON

    JSON.parse("{name: Ravi}");

    This causes an error because:

    • Keys must be in double quotes

    Error 2: Forgetting JSON.parse()

    let data = localStorage.getItem("user");

    console.log(data.name); // undefined

    Reason:

    • data is still a string

    Error 3: Storing Objects Directly

    localStorage.setItem("user", user);

    Result:

    [object Object]

    Always use JSON.stringify().

    Handling JSON Safely Using try-catch

Safe JSON Parsing Example

Uses try-catch to safely parse JSON and handle invalid data.

try {
  let data = JSON.parse(jsonString);
  console.log(data);
} catch (error) {
  console.log("Invalid JSON format");
}
  • This prevents application crashes.

    Best Practices for JSON Handling

    • Always validate JSON before parsing

    • Use try-catch with JSON.parse()

    • Avoid deeply nested JSON

    • Keep JSON clean and structured

    • Convert objects before storage

    • Remove unused JSON data

    Real-World Use Cases

    • Login user data storage

    • Shopping cart data

    • API communication

    • User preferences

    • Session handling