JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JSON Objects


JSON objects are one of the most essential parts of working with data in modern web development. Whether you are fetching data from an API, storing configuration, or passing data between client and server, JSON objects allow you to structure your data clearly and efficiently.

What is a JSON Object?

A JSON object is a collection of key/value pairs enclosed in curly braces {}.

  • Keys must always be strings, written inside double quotes " ".

  • Values can be any valid JSON data type: string, number, boolean, array, object, or null.

  • Objects can be nested inside other objects to represent complex data.

Basic Example:

{
  "name": "Vicky",
  "age": 28,
  "isDeveloper": true
}

Here:

  • "name" → String

  • "age" → Number

  • "isDeveloper" → Boolean

JSON objects make it easy to represent structured information in a readable way.

Creating JSON Objects in JavaScript

You can create JSON objects in two main ways:

1. Using Object Literal Syntax

let user = {
  name: "Vicky",
  age: 28,
  isDeveloper: true
};

This is the most common method. It allows you to directly write the object in code.

2. Using JSON.parse() on a String

let jsonString = '{"name": "Sanjana", "age": 26, "isDeveloper": false}';
let user = JSON.parse(jsonString);

This is useful when data comes as a JSON string, for example, from a server or API.

Accessing Values in JSON Objects

Once you have a JSON object, you can access its values in two ways:

Dot Notation

console.log(user.name); // Output: Vicky
console.log(user.age);  // Output: 28

Bracket Notation

console.log(user["name"]); // Output: Vicky
console.log(user["age"]);  // Output: 28

Tip: Bracket notation is useful if:

  • The key contains spaces or special characters.

  • The key is stored in a variable.

let key = "isDeveloper";
console.log(user[key]); // Output: true

Adding, Updating, and Deleting Properties

JSON objects are dynamic. You can add new properties, update existing ones, or delete them.

let user = { name: "Vicky", age: 28 };

// Add a new property
user.city = "Mumbai";

// Update an existing property
user.age = 29;

// Delete a property
delete user.city;

console.log(user);

Output:

{ "name": "Vicky", "age": 29 }

This flexibility allows you to modify data on the fly, which is essential for dynamic web applications.

Nested JSON Objects

Objects can contain other objects, forming nested structures. Nested objects are perfect for representing real-world entities like user profiles, products, or orders.

let user = {
  name: "Vicky",
  age: 28,
  address: {
    city: "Mumbai",
    zipcode: 400001
  }
};

console.log(user.address.city);    // Output: Mumbai
console.log(user.address.zipcode); // Output: 400001

Nested objects allow you to organize data hierarchically, making it more logical and easier to manage.

Iterating Over JSON Objects

You can loop through a JSON object to access keys and values.

Using for…in Loop

let user = { name: "Vicky", age: 28, isDeveloper: true };

for (let key in user) {
  console.log(key + ": " + user[key]);
}

Output:

name: Vicky
age: 28
isDeveloper: true

Using Object.keys() and forEach()

Object.keys(user).forEach(key => {
  console.log(key + ": " + user[key]);
});

This modern approach is cleaner and works well in large applications.

Converting JSON Objects to Strings

When sending JSON objects to a server or saving them in storage, you need to convert them to strings using JSON.stringify():

let user = { name: "Vicky", age: 28, isDeveloper: true };
let jsonString = JSON.stringify(user);
console.log(jsonString);

Output:

{"name":"Vicky","age":28,"isDeveloper":true}

This allows you to store or transmit data in a format that other systems can understand.

Real-World Example: User Profile

let userProfile = {
  username: "vicky123",
  email: "vicky@example.com",
  roles: ["Admin", "Editor"],
  address: {
    city: "Mumbai",
    country: "India"
  },
  isActive: true
};

// Access nested values
console.log(userProfile.address.country); // Output: India

// Add a new property
userProfile.phone = "9876543210";

// Loop through roles
userProfile.roles.forEach(role => console.log(role));

This example shows how JSON objects can store complex data and be manipulated easily.

Advanced Tips for Working with JSON Objects

  1. Check if a property exists

if ("email" in userProfile) {
  console.log("Email exists:", userProfile.email);
}
  1. Get all values as an array

console.log(Object.values(userProfile));
  1. Merge two JSON objects

let user1 = { name: "Vicky", age: 28 };
let user2 = { city: "Mumbai", isDeveloper: true };
let mergedUser = { ...user1, ...user2 };
console.log(mergedUser);
  1. Deep copy an object

let copy = JSON.parse(JSON.stringify(userProfile));

This ensures you don’t accidentally modify the original object.

Summary of the Tutorial

  • JSON objects are collections of key/value pairs inside {}.

  • Keys are strings; values can be any JSON data type.

  • Objects can be created directly or using JSON.parse() from a string.

  • Access properties with dot or bracket notation.

  • Add, update, delete, iterate, and merge objects as needed.

  • Nested objects help represent complex data.

  • Use JSON.stringify() to convert objects into strings for storage or transmission.

Mastering JSON objects is essential for managing structured data, interacting with APIs, and building dynamic web applications.


Practice Questions

  1. Create a JSON object for a user with keys: name (string), age (number), isActive (boolean), and city (string). Then print the user’s city using dot notation.

  2. Convert this JSON string into a JavaScript object and print the user’s name and age:

'{"name":"Sanjana","age":26,"isDeveloper":false}'
  1. Add a new property phone to the following object and print the updated object:

let user = { name: "Vicky", age: 28, isDeveloper: true };
  1. Update the age property of this object to 30 and print the result:

let user = { name: "Sanjana", age: 25, city: "Delhi" };
  1. Delete the city property from this object and print the remaining keys and values:

let user = { name: "Vicky", age: 28, city: "Mumbai" };
  1. Create a nested JSON object representing a product with name, price, and manufacturer (object with name and location). Access the manufacturer’s name using dot notation.

  2. Loop through the following object and print all keys and values:

let user = { name: "Sanjana", age: 26, isDeveloper: true };
  1. Merge these two JSON objects into a single object and print the result:

let obj1 = { name: "Vicky", age: 28 };
let obj2 = { city: "Mumbai", isDeveloper: true };
  1. Convert the following object into a JSON string using JSON.stringify() and print it:

let user = { name: "Sanjana", age: 26, skills: ["HTML", "CSS", "JS"] };
  1. Deep copy this object using JSON.parse(JSON.stringify()), then update the copy’s age without changing the original object:

let user = { name: "Vicky", age: 28, city: "Mumbai" };

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top