Skip to Content
JavaScriptBasicWorking with JSON

JSON Basics 📦

JSON (JavaScript Object Notation) is the go-to format for web APIs.

1) Parsing JSON 🔍

const response = '{"name":"Mina","age":21}'; const data = JSON.parse(response); console.log(data.name);
  • JSON.parse converts a JSON string into a JavaScript value.
  • Wrap in try...catch to handle malformed payloads.

2) Stringifying JSON 🧾

const payload = { name: "Mina", age: 21 }; const body = JSON.stringify(payload); fetch("/api/users", { method: "POST", body });
  • Use JSON.stringify(value, null, 2) for pretty-printed output.
  • Dates become strings; functions/symbols get dropped.

3) Fetching APIs 🌐

const users = await fetch("/api/users") .then(res => res.json());
  • Response.json() already parses; no need to call JSON.parse again.
  • Validate shapes with TypeScript or runtime schema libraries (Zod, Yup).

4) Deep Cloning 🧬

  • JSON.parse(JSON.stringify(obj)) creates a simple deep clone but loses functions, Dates, and undefined values.
  • Prefer structuredClone(obj) when available.

5) Security Tip 🔐

  • Never eval JSON. Always use JSON.parse or streaming parsers.
  • Sanitize user-generated JSON before storing/echoing back.

Key Takeaways ✅

  • JSON is text; parse to use it, stringify to send it.
  • Handle parsing errors and shape validation to avoid runtime crashes.
  • Use modern cloning APIs for complex data when possible.

Recap 🔄

Mastering JSON.parse, JSON.stringify, and fetch workflows keeps data flowing cleanly between your frontend and backend services.

Last updated on