iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JSON Objects

JSON objects look like JavaScript object literals — with two strict rules: keys are always double-quoted strings, and no trailing commas.

Valid forms

JSON
{ "name": "Ada Lovelace", "age": 36 }

// Nested
{
  "user": {
    "id": 1,
    "name": "Ada",
    "address": { "city": "London", "country": "UK" }
  }
}

// Arrays as values
{ "tags": ["math", "code"], "scores": [90, 95, 100] }

// Mixed
{ "version": 1, "active": true, "lastSeen": null }

// Empty
{}

Common mistakes

Invalid JSON — all of these throw
{ name: "Ada" }                 // ❌ unquoted key
{ 'name': 'Ada' }               // ❌ single quotes
{ "a": 1, }                     // ❌ trailing comma
{ "n": undefined }              // ❌ undefined not allowed
{ "x": 0.1, /* comment */ }     // ❌ comments not allowed

Parse and traverse

JS
const text = '{"user":{"name":"Ada","address":{"city":"London"}}}';
const data = JSON.parse(text);

data.user.name;                       // "Ada"
data.user.address?.city ?? "—";       // safe nested access

// Pick a sub-tree
const { user: { address } } = data;
address.city;                         // "London"

Convert between objects and JSON

JS
// Object → JSON
const text = JSON.stringify(obj, null, 2);

// JSON → object (safe)
const safeParse = (s, fallback = null) => {
  try { return JSON.parse(s); } catch { return fallback; }
};
Tip: When designing API responses, prefer flat objects over deep nesting. Easier to type, easier to evolve, friendlier to TypeScript inference.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JSON Objects!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Choose the quote character JSON keys require.

{ name : Ada }

Test yourself

Q1. JSON object keys must be…
Q2. Comments in JSON are…
Q3. A safe parse helper should…

Discussion

Loading…