One of the most useful features of JSON is nesting.
Nesting means placing an object or an array inside another object or array. This helps organize related information and represent real-world data in a clear way.
For example, a school has students, and each student has subjects. Instead of putting everything in one long list, we can group related information together using nesting.
An object can contain another object.
This is useful when you want to group related information together.
For example, a person has an address.
{
"person": {
"name": "Emma",
"address": {
"city": "Colombo",
"country": "Sri Lanka"
}
}
}
Here:
person is an object.person, address is another object.This makes the data organized and easy to understand.
An array can contain multiple objects.
This is useful when you have many similar items, such as students, books, or products.
{
"students": [
{
"name": "Liam",
"grade": 8
},
{
"name": "Sophia",
"grade": 9
},
{
"name": "Noah",
"grade": 8
}
]
}
Here:
students is an array.This is one of the most common ways JSON is used.
An object can also contain an array.
Use this when one piece of information has multiple values.
{
"book": {
"title": "Science Basics",
"chapters": [
"Plants",
"Animals",
"Space"
]
}
}
Here:
book is an object.chapters is an array because the book has several chapters.An array can contain other arrays.
This is useful for storing data in rows and columns.
{
"classrooms": [
["Room A", "Room B"],
["Room C", "Room D"]
]
}
Each inner array represents one row.
In real applications, JSON often combines objects and arrays.
For example, a school has many students, and each student studies several subjects.
{
"school": {
"name": "Green Valley School",
"students": [
{
"name": "Emma",
"subjects": [
"Math",
"Science"
]
},
{
"name": "Leo",
"subjects": [
"English",
"History"
]
}
]
}
}
In this example:
school is an object.students is an array.subjects is another array inside each student object.This shows how objects and arrays can work together to organize complex information.
JSON allows you to keep nesting objects and arrays inside one another.
For example:
{
"library": {
"sections": [
{
"name": "Science",
"books": [
{
"title": "Physics Basics",
"author": {
"firstName": "John",
"lastName": "Lee"
}
}
]
}
]
}
}
This example has several levels of nesting:
library → objectsections → arraybooks → arrayauthor → objectJSON allows many levels of nesting, but using too many levels can make the data difficult to read. It is usually better to keep the structure as simple as possible.
Nesting helps organize related information in JSON.
You can nest data in several ways:
By combining objects and arrays, JSON can represent simple data as well as complex real-world information in a clear and organized way.