JSON in JavaScript
1. Simple Explanation
JSON (JavaScript Object Notation) is a lightweight, text‑based format for representing structured data.
- It’s language‑agnostic yet closely resembles JavaScript object literals.
- JSON is used to exchange data between a client (browser) and a server, to store configuration files, and to persist data in browsers (
localStorage,IndexedDB, etc.).
When you see a string that looks like an object:
{
"name": "Alice",
"age": 30,
"skills": ["JS", "React"]
}
that’s JSON – it can be parsed into a real JavaScript object.
2. Key Points
| Concept | What It Means | Why It Matters |
|---|---|---|
| JSON Structure | Objects ({}) and arrays ([]) with key/value pairs. |
Forms the data you send/receive. |
| Data Types | string, number, boolean, null, array, object. |
Determines how data is stored and parsed. |
| Syntax Rules | • Keys must be double‑quoted. • Strings must be double‑quoted. • No comments, trailing commas, or functions. |
Keeps JSON simple and safe. |
| Parsing | JSON.parse(string) → JavaScript object. |
Converts incoming JSON text to usable JS. |
| Stringifying | JSON.stringify(obj, replacer, space) → JSON string. |
Converts JS data to JSON for storage or transfer. |
| Error Handling | JSON.parse throws if string is invalid. |
Must guard against bad data. |
| Circular References | JSON.stringify fails on circular structures. |
Avoid or use custom replacer. |
| Common APIs | fetch(url).then(r => r.json()) localStorage.setItem(key, JSON.stringify(obj)) |
Typical patterns in web apps. |
| Security | JSON is safe – no code execution. | Prefer over eval() or new Function(). |
3. Worked Example
We’ll build a small flow:
- Create a JavaScript object.
- Convert it to a JSON string.
- Store it in
localStorage. - Retrieve and parse it back into an object.
- Send it to a mock API via
fetch.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>JSON Example</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>
// app.js
// 1️⃣ Create an object
const user = {
id: 101,
name: "John Doe",
email: "john