If we want to store data multiple for multiple objects; i.e multiple employees then we can use a JSON array since a JSON array can contain multiple objects.
Example of a JSON array:
var employeesJSON = [
{
"firstName": "Tom",
"lastName": "Baker"
},
{
"firstName": "Sara",
"lastName": "Grover"
}];
Notice that
- We used [ ] square brackets to specify that we are making an array of objects
- We used curly braces { }, to seperate each object (employee)
Another way of achieving the same result without creating an array, is using a nested JSON object:
var employeesJSON = {
"Tom": {
"firstName": "Tom",
"lastName": "Baker",
},
"Sara": {
"firstName": "Sara",
"lastName": "Grover"
}
};
Notice that here:
- We seperated each object (employee) by using their name as follows "Tom":{ ... } , "Sara:" {...}
Retriving nested data from a nested JSON object.
- Type the following code to retrive and store the last name of the employee Tom to a variable.
var result = employeesJSON.Tom.lastName;