What are Nesting Structures?
In JSON, objects and arrays can be nested within each other to form complex data structures. This is one of JSON's most powerful features, allowing representation of complex real-world relationships.
Nesting Example: User Info
{
"users": [
{
"id": 1,
"name": "John Doe",
"contacts": [
{ "type": "email", "value": "[email protected]" },
{ "type": "phone", "value": "13800138000" }
]
}
],
"total": 1,
"success": true
}
Common Nesting Patterns
1. Object inside Object
A property value of an object is another object:
{
"user": {
"name": "John",
"profile": {
"age": 30,
"city": "London"
}
}
}
2. Array inside Object
A property value of an object is an array:
{
"product": {
"name": "Laptop",
"tags": ["Electronics", "Office", "Computer"],
"specifications": ["16GB RAM", "512GB SSD", "i7 Processor"]
}
}
3. Object inside Array
Array elements are objects:
{
"orders": [
{ "id": 1, "total": 99.99 },
{ "id": 2, "total": 149.99 },
{ "id": 3, "total": 79.99 }
]
}
4. Multi-level Nesting
Multi-level combinations of objects and arrays:
{
"company": {
"name": "Tech Corp",
"departments": [
{
"name": "R & D",
"employees": [
{ "name": "Alice", "role": "Engineer" },
{ "name": "Bob", "role": "Designer" }
]
}
]
}
}
Accessing Nested Data
To access nested data, you need to traverse level by level. Different languages have different syntax:
JavaScript
// Accessing nested property
data.user.profile.city
// Accessing array element
data.users[0].name
Python
# Accessing nested property
data['user']['profile']['city']
# Accessing array element
data['users'][0]['name']
Interactive Exercise: Complex Nesting
Create a JSON with multi-level nesting describing a school structure:
- School name
- Contains multiple classes (array)
- Each class contains student info (array of objects)
- Student info includes name, age, scores etc.
🎉 Fundamentals Completed!
You have mastered the basic concepts of JSON. Now let's apply this knowledge in actual programming.
Start Practical Application →