Working with JSON in JavaScript - potatoscript/json GitHub Wiki
๐ฏ Working with JSON in JavaScript: Your Magical Toolkit! ๐งโโ๏ธ๐ป
Welcome to the JSON & JavaScript Adventure! ๐
Imagine you're a wizard ๐ฎ and JSON is your magic spellbook.
With JavaScript as your wand ๐ช, you can read, write, and control JSON easily!
By the end of this adventure, you'll be a JSON JavaScript Master! ๐
๐ What is JSON in JavaScript?
JSON (JavaScript Object Notation) is like a super organized diary that stores information. ๐
JavaScript can read from, modify, and save information in JSON with ease!
๐ฏ Example: Basic JSON Data
{
"name": "Lucy",
"age": 25,
"hobbies": ["reading", "coding", "traveling"]
}
๐ Explanation:
nameโ Key with value"Lucy"(string) ๐ageโ Key with value25(number) ๐ขhobbiesโ Key with an array of values ๐๐ฅ๏ธโ๏ธ
โก Why Use JSON in JavaScript?
โ
Data Exchange: Send and receive data between a web server and client.
โ
API Integration: Connect web applications with APIs using JSON.
โ
Local Storage: Save and retrieve user data in the browser.
๐ฅ 1. Parsing JSON with JSON.parse()
Imagine you receive JSON data as a string from a web server. ๐ฉ
To use it in JavaScript, convert it into an object with JSON.parse()! ๐งโโ๏ธ
๐ฏ Example: Parsing JSON String
let jsonString = '{ "name": "Lucy", "age": 25, "hobbies": ["reading", "coding", "traveling"] }';
// Parse JSON string to JavaScript object
let person = JSON.parse(jsonString);
console.log(person.name); // Output: Lucy
console.log(person.age); // Output: 25
console.log(person.hobbies[1]); // Output: coding
๐ Explanation:
JSON.parse()converts the JSON string into a JavaScript object.- Now
personis a JavaScript object with all the data. ๐ฏ
โจ 2. Creating JSON with JSON.stringify()
When you want to send data to a server, you convert your JavaScript object into a JSON string. ๐ค
Use JSON.stringify() to convert an object to a string. ๐
๐ฏ Example: Converting Object to JSON String
let person = {
name: "Lucy",
age: 25,
hobbies: ["reading", "coding", "traveling"]
};
// Convert JavaScript object to JSON string
let jsonString = JSON.stringify(person);
console.log(jsonString);
// Output: {"name":"Lucy","age":25,"hobbies":["reading","coding","traveling"]}
๐ Explanation:
JSON.stringify()converts a JavaScript object into a JSON string.- This makes it ready to be sent over the internet or stored locally. ๐
๐ง 3. Accessing JSON Data in JavaScript
Once you parse a JSON string into an object, you can easily access the data! ๐
๐ฏ Example: Accessing Data
let person = {
name: "Lucy",
age: 25,
hobbies: ["reading", "coding", "traveling"]
};
console.log(person.name); // Output: Lucy
console.log(person["age"]); // Output: 25
console.log(person.hobbies[0]); // Output: reading
๐ต๏ธโโ๏ธ Two Ways to Access Data:
- Dot Notation:
person.name - Bracket Notation:
person["age"]
๐งฉ 4. Modifying JSON Data
You can easily modify the data inside a JSON object! ๐ ๏ธ
๐ฏ Example: Modifying JSON Data
let person = {
name: "Lucy",
age: 25,
hobbies: ["reading", "coding", "traveling"]
};
// Modify properties
person.name = "Berry";
person.age += 1;
person.hobbies.push("gaming");
console.log(person);
๐ Result:
{
"name": "Berry",
"age": 26,
"hobbies": ["reading", "coding", "traveling", "gaming"]
}
๐น๏ธ 5. Adding and Deleting Properties
Want to add or delete something from your JSON object? No problem! ๐ฅ
๐ฏ Example: Add New Property
person.country = "Japan";
console.log(person.country); // Output: Japan
๐ฏ Example: Delete Property
delete person.age;
console.log(person.age); // Output: undefined
๐ฐ๏ธ 6. Looping Through JSON Objects
You can loop through JSON objects to read and display data dynamically. ๐
๐ฏ Example: Looping Through an Object
let person = {
name: "Lucy",
age: 25,
hobbies: ["reading", "coding", "traveling"]
};
// Loop through keys in the object
for (let key in person) {
console.log(key + ": " + person[key]);
}
๐ Result:
name: Lucy
age: 25
hobbies: reading,coding,traveling
๐ฆ 7. JSON Arrays and Looping
When you have multiple items stored as an array, loop through them easily! ๐ฅ
๐ฏ Example: Looping Through JSON Array
let people = [
{ "name": "Lucy", "age": 25 },
{ "name": "Berry", "age": 26 },
{ "name": "Snoopy", "age": 5 }
];
// Loop through array
people.forEach(person => {
console.log(person.name + " is " + person.age + " years old.");
});
๐ Result:
Lucy is 25 years old.
Berry is 26 years old.
Snoopy is 5 years old.
๐ต๏ธโโ๏ธ 8. Nested JSON Objects in JavaScript
Sometimes JSON data has nested objects inside. You can easily navigate them. ๐งญ
๐ฏ Example: Accessing Nested JSON
let person = {
name: "Lucy",
address: {
city: "Fukuoka",
country: "Japan"
}
};
console.log(person.address.city); // Output: Fukuoka
๐งช 9. JSON with AJAX for API Calls
You can use JavaScript to get JSON data from APIs using AJAX or Fetch API! ๐
๐ฏ Example: Fetch JSON from API
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
๐ Explanation:
fetch()makes a request to the API.response.json()converts the response to JSON.- Data is logged or processed further.
๐๏ธ 10. Storing and Retrieving JSON in Local Storage
You can store JSON data locally in the browser using localStorage. ๐๏ธ
๐ฏ Example: Store and Retrieve JSON
let user = { name: "Lucy", age: 25 };
// Save to local storage
localStorage.setItem("user", JSON.stringify(user));
// Retrieve from local storage
let storedUser = JSON.parse(localStorage.getItem("user"));
console.log(storedUser.name); // Output: Lucy
๐ Error Handling in JSON
When working with JSON, things may go wrong! Handle errors with try...catch. ๐ฅ
๐ฏ Example: JSON Error Handling
let invalidJson = "{ name: 'Lucy' }"; // Invalid JSON!
try {
let data = JSON.parse(invalidJson);
} catch (error) {
console.error("Oops! JSON error:", error);
}