๐๏ธ Working with JSON in JavaScript
JSON (JavaScript Object Notation) is a lightweight data format used to exchange data between a client and a server. It is easy to read, write, and parse using JavaScript.
๐ JSON Format Example
{
"name": "Alice",
"age": 25,
"skills": ["HTML", "CSS", "JavaScript"]
}
๐ Converting Between JSON and JS
โ JSON to JavaScript Object
const jsonString = '{"name":"Alice","age":25}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Alice
โ JavaScript Object to JSON
const person = { name: "Bob", age: 30 };
const json = JSON.stringify(person);
console.log(json); // {"name":"Bob","age":30}
๐งช JSON with fetch()
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => {
console.log(data.title);
});
๐ซ JSON Tips & Warnings
- Keys and string values must be in double quotes
" "
- No comments allowed in JSON
- Use
try...catch
when parsing JSON
try {
const obj = JSON.parse('{"name":"Eve"}');
console.log(obj.name);
} catch (error) {
console.error("Invalid JSON:", error);
}
๐ก Next Step: Learn how to use
async/await
with fetch for cleaner API calls!