07 Objects

A JSON object is a collection of key-value pairs.

Use an object when you want to store different pieces of information about one thing.

For example, if you want to store information about a book, you can use an object.

{
    "title": "The Hobbit",
    "author": "J.R.R. Tolkien",
    "pages": 310
}

This object stores three pieces of information about one book.

Objects Can Contain Arrays

Sometimes one piece of information needs multiple values. In this case, you can store an array inside an object.

For example, a student can study more than one subject.

{
    "student": {
        "name": "Sophia",
        "subjects": [
            "Math",
            "Science",
            "History"
        ]
    }
}

Here:

  • student is an object.
  • subjects is an array because the student studies more than one subject.

Objects Can Contain Other Objects

An object can also contain another object. This is called a nested object.

For example, a company has an employee, and the employee has an address.

{
    "employee": {
        "name": "David",
        "address": {
            "city": "London",
            "country": "United Kingdom"
        }
    }
}

Here:

  • employee is an object.
  • Inside it, address is another object.

This helps organize related information neatly.

Rules for JSON Objects

Rule 1: Objects Use Curly Braces { }

Every object must start with { and end with }.

✅ Correct

{
    "planet": "Earth"
}

❌ Wrong

[
    "planet": "Earth"
]

Why is it wrong? Square brackets ([]) are used for arrays, not objects.

Rule 2: Objects Store Key-Value Pairs

Each piece of information must have a key and a value.

✅ Correct

{
    "brand": "Samsung"
}

❌ Wrong

{
    "brand"
}

Why is it wrong? The key brand does not have a value.

Rule 3: Separate Key-Value Pairs with Commas

If an object has more than one key-value pair, separate them with commas.

✅ Correct

{
    "name": "Olivia",
    "age": 15
}

❌ Wrong

{
    "name": "Olivia"
    "age": 15
}

Why is it wrong? There is no comma between the two key-value pairs.

Rule 4: Objects Can Be Empty

An object does not have to contain any data.

✅ Correct

{}

This is called an empty object.

Rule 5: Objects Can Be Nested

You can place one object inside another object.

✅ Correct

{
    "car": {
        "brand": "Toyota",
        "year": 2024
    }
}

This is useful for grouping related information together.

Summary

An object is best used when you want to describe one item using multiple pieces of information.

For example:

  • A student → name, age, grade
  • A book → title, author, pages
  • A car → brand, model, year

Remember

  • ✅ Objects use curly braces {}.
  • ✅ They store key-value pairs.
  • ✅ They can contain arrays.
  • ✅ They can contain other objects.
  • ✅ They can even be empty ({}).