Lesson 20 of 158 – JSON Objects and Arrays
20%

JSON Objects and Arrays

In the previous lesson, we learned the basics of JSON. In this lesson, we will learn how to work with JSON objects and JSON arrays. These two structures are extremely important when working with REST APIs.

A REST API can return one object, an array of objects, or a complex combination of objects and arrays. React Native applications commonly use these structures to display users, students, products, posts, and other data.

Note: JSON objects use { }, while JSON arrays use [ ]. Objects store data using key-value pairs, while arrays store multiple values in an ordered collection.

1. What is a JSON Object?

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


{
    "name": "Rahul",
    "age": 22,
    "city": "Patna"
}

Here, name, age, and city are keys. Their corresponding values are Rahul, 22, and Patna.

2. JSON Object Structure

The basic structure of a JSON object looks like this:


{
    "key": "value"
}

Multiple properties can be added using commas.


{
    "name": "Rahul",
    "age": 22,
    "course": "React Native"
}

3. JSON Object with Different Data Types

A JSON object can contain different types of values.


{
    "name": "Rahul",
    "age": 22,
    "active": true,
    "middleName": null
}

The object contains a string, number, Boolean value, and null value.

4. Accessing Object Properties

When JSON is converted into a JavaScript object, its properties can be accessed using dot notation.


const student = {
    "name": "Rahul",
    "age": 22
};

console.log(student.name);
console.log(student.age);

The output will be:


Rahul
22

5. Accessing Properties Using Brackets

JavaScript also allows object properties to be accessed using bracket notation.


const student = {
    "name": "Rahul",
    "age": 22
};

console.log(student["name"]);
console.log(student["age"]);

Bracket notation is particularly useful when the property name is stored in a variable.

6. What is a JSON Array?

A JSON array is an ordered collection of values enclosed inside square brackets [ ].


[
    "HTML",
    "CSS",
    "JavaScript",
    "React Native"
]

Each value is separated by a comma.

7. JSON Array of Strings

An array can contain multiple string values.


[
    "Apple",
    "Banana",
    "Mango",
    "Orange"
]

The values are stored in a specific order.

8. JSON Array of Numbers

A JSON array can contain numeric values.


[
    10,
    20,
    30,
    40,
    50
]

Numbers do not need quotation marks.

9. JSON Array of Boolean Values

A JSON array can also contain Boolean values.


[
    true,
    false,
    true,
    false
]

Boolean values are written as true or false without quotation marks.

10. JSON Array Index

When JSON arrays are converted into JavaScript arrays, their elements are accessed using indexes.


const courses = [
    "HTML",
    "CSS",
    "JavaScript"
];

console.log(courses[0]);
console.log(courses[1]);
console.log(courses[2]);

The first element has index 0.

11. JSON Array of Objects

One of the most important JSON structures in REST APIs is an array containing multiple objects.


[
    {
        "id": 1,
        "name": "Rahul"
    },
    {
        "id": 2,
        "name": "Amit"
    }
]

Each array element is a separate object.

12. Accessing an Object from an Array

Suppose we have an array of students.


const students = [
    {
        "id": 1,
        "name": "Rahul"
    },
    {
        "id": 2,
        "name": "Amit"
    }
];

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

The output is:


Rahul

13. Nested JSON Objects

A JSON object can contain another JSON object.


{
    "name": "Rahul",
    "address": {
        "city": "Patna",
        "state": "Bihar"
    }
}

The address property contains another object.

14. Accessing Nested Objects

Nested properties can be accessed using multiple dot operators.


const student = {
    "name": "Rahul",
    "address": {
        "city": "Patna",
        "state": "Bihar"
    }
};

console.log(student.address.city);
console.log(student.address.state);

15. Object Containing an Array

A JSON object can contain an array as one of its properties.


{
    "name": "Rahul",
    "skills": [
        "HTML",
        "CSS",
        "JavaScript"
    ]
}

The skills property contains an array.

16. Accessing an Array Inside an Object


const student = {
    "name": "Rahul",
    "skills": [
        "HTML",
        "CSS",
        "JavaScript"
    ]
};

console.log(student.skills[0]);
console.log(student.skills[1]);

The output will be:


HTML
CSS

17. Array Containing Nested Arrays

JSON arrays can contain other arrays.


[
    [10, 20],
    [30, 40],
    [50, 60]
]

This creates a nested array structure.

18. Mixed JSON Array

A JSON array can contain different JSON value types.


[
    "Rahul",
    22,
    true,
    null
]

However, in REST API responses, arrays of objects are often more useful for structured application data.

19. Students API Response

A student API may return an object containing a students array.


{
    "success": true,
    "students": [
        {
            "id": 1,
            "name": "Rahul",
            "course": "React Native"
        },
        {
            "id": 2,
            "name": "Amit",
            "course": "PHP"
        }
    ]
}

This is a common REST API response structure.

20. Accessing API Array Data

After receiving JSON data in JavaScript, an array can be accessed through its property.


const data = {
    "students": [
        {
            "id": 1,
            "name": "Rahul"
        },
        {
            "id": 2,
            "name": "Amit"
        }
    ]
};

console.log(data.students[0].name);

The output is Rahul.

21. Looping Through JSON Arrays

JavaScript can use a loop to process every object inside an array.


const students = [
    {
        "id": 1,
        "name": "Rahul"
    },
    {
        "id": 2,
        "name": "Amit"
    }
];

students.forEach(function(student) {
    console.log(student.name);
});

22. JSON Arrays with React Native FlatList

React Native's FlatList is commonly used to display arrays returned by REST APIs.


const students = [
    {
        id: 1,
        name: "Rahul"
    },
    {
        id: 2,
        name: "Amit"
    }
];

<FlatList
    data={students}
    keyExtractor={item => item.id.toString()}
    renderItem={({item}) => (
        <Text>{item.name}</Text>
    )}
/>

This is especially useful when displaying large lists of API data.

23. JSON Object from PHP

PHP can create an array and convert it into a JSON object using json_encode().


$data = [
    "id" => 1,
    "name" => "Rahul",
    "course" => "React Native"
];

header("Content-Type: application/json");

echo json_encode($data);

The PHP API can return this data to the mobile application.

24. PHP Array of Students

PHP can also create an array containing multiple student records.


$students = [
    [
        "id" => 1,
        "name" => "Rahul"
    ],
    [
        "id" => 2,
        "name" => "Amit"
    ]
];

echo json_encode($students);

The result is a JSON array containing objects.

25. JSON Object with API Metadata

An API response can contain metadata along with the actual data.


{
    "success": true,
    "message": "Students found",
    "total": 2,
    "students": [
        {
            "id": 1,
            "name": "Rahul"
        },
        {
            "id": 2,
            "name": "Amit"
        }
    ]
}

This structure gives the mobile application both information and metadata about the response.

26. Objects and Arrays in POST Requests

A mobile application can send an object containing an array to a REST API.


{
    "name": "Rahul",
    "skills": [
        "React Native",
        "TypeScript",
        "PHP"
    ]
}

The PHP API can decode the JSON request and process the values.

27. Objects and Arrays with Fetch


const response = await fetch(
    "https://example.com/api/students"
);

const data = await response.json();

data.students.forEach(student => {
    console.log(student.name);
});

The response is converted into a JavaScript object, and the students array can then be processed.

28. Common Objects and Arrays Mistakes

  • Using curly braces when an array is required.
  • Using square brackets when an object is required.
  • Forgetting commas between properties.
  • Using an incorrect array index.
  • Trying to access a property that does not exist.
  • Forgetting that array indexes start from 0 in JavaScript.
  • Incorrectly accessing nested objects.
  • Assuming every API response has the same structure.

29. Complete REST API JSON Structure


{
    "success": true,
    "message": "Students found",
    "data": {
        "total": 2,
        "students": [
            {
                "id": 1,
                "name": "Rahul",
                "course": "React Native",
                "skills": [
                    "JavaScript",
                    "TypeScript"
                ]
            },
            {
                "id": 2,
                "name": "Amit",
                "course": "PHP",
                "skills": [
                    "PHP",
                    "MySQL"
                ]
            }
        ]
    }
}

This example demonstrates objects, arrays, nested objects, and nested arrays together.

30. Complete JSON Objects and Arrays Concept

JSON objects and arrays form the foundation of REST API data communication.

A typical mobile application receives an object from the API. That object may contain arrays of students, products, courses, messages, or other records.


API Response
     ↓
JSON Object
     ↓
JSON Array
     ↓
Array of Objects
     ↓
React Native
     ↓
FlatList / Components

Understanding objects and arrays is essential before learning how to retrieve and display REST API data in React Native.

📌 Key Points

  • JSON objects use curly braces { }.
  • JSON arrays use square brackets [ ].
  • Objects contain key-value pairs.
  • Arrays contain ordered values.
  • Array indexes start from 0 in JavaScript.
  • An array can contain multiple objects.
  • An object can contain an array.
  • Objects can contain nested objects.
  • Arrays can contain nested arrays.
  • REST APIs frequently return arrays of objects.
  • PHP can create JSON using json_encode().
  • React Native can process API arrays using JavaScript.
  • FlatList is commonly used to display API arrays in React Native.
  • Correctly understanding the API response structure is important for mobile application development.

🧠 Quick Quiz

Question: Which symbols are used to create a JSON array?