In this JSON document, we have information about children enrolled in a summer camp.
Data Handling
1. 'data.children[0]' accesses the array of chldin in the 'data' object and retrives the first child
firstChild.name.firstName and firstChild.name.lastName: Accesses the nested name object to get the first name and last name of the child.
firstChild.age: Accesses the age property of the child.
The console.log statements displays the retrieved information
const firstChild = data.children[0];
console.log("First child's name:", firstChild.name.firstName, firstChild.name.lastName);
console.log("First child's age:", firstChild.age);
Now lets apply all this to our JSON document
Data Manipulation
const newChild = { ... }: Defines a new child object with the specified properties.
data.children.push(newChild): Adds the new child to the array of children in the data object.
// Adding a new child to the data
const newChild = {
childID: 987654321,
name: { firstName: "Emma", lastName: "Smith" },
age: 9,
gender: "Female",
address: { street: "789 Avenue", city: "Thunder Bay", province: "Ontario", zip: "L2B 3C4" },
dietaryRestrictions: { allergy: "Milk", restrictions: "None" },
medicalInformation: { medication: "Asthma inhaler", medicalCondition: "Asthma" },
contact: { parentsName: "Michael Smith", parentPhone: "555-555-5555" },
emergencyContact: { emergencyName: "Michael Smith", emergencyNumber: "123-456-7890" },
campProgram: "Nature Explorer",
};
data.children.push(newChild);
Now lets apply it to our JSON document
Serializing/Deserialization
// Serializing the data to JSON
const jsonData = JSON.stringify(data, null, 2);
// Deserializing JSON back to a JavaScript object
const parsedData = JSON.parse(jsonData);
// Checking if the deserialized data is the same as the original data
console.log("Is data equal to parsedData?", JSON.stringify(data) === JSON.stringify(parsedData));
JSON.stringify(data, null, 2): Converts the data object to a JSON-formatted string with an indentation of 2 spaces. This is useful for readability.
JSON.parse(jsonData): Parses the JSON-formatted string (jsonData) back into a JavaScript object.
The console.log statement checks if the deserialized data is equal to the original data. This is done by comparing the JSON-formatted strings of the original and parsed data.
Now lets apply this to our JSON document