SmartCodingTips

๐Ÿ—‚๏ธ 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!