Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
APIs APIs From Zero to Real-World API Testing & Automation JSON Module 2 — JSON and Data

JSON Objects, Arrays, and Nested Data — Working with Complex JSON

Reviewed & accurate
AI Summary

What You'll Learn

  • How JSON objects and arrays combine
  • How to read nested JSON step by step
  • Common patterns: arrays of objects, objects inside objects
  • How to access nested values in code

Why This Matters

Real API responses are rarely flat. A user response has an address object, which has a city. A list of orders has an array, each order has items, each item has a product. If you cannot navigate nested JSON, you cannot extract the data you need from any non-trivial API.

Objects and Arrays — The Two Building Blocks

JSON has two compound types that can hold other values:

  • Object — a collection of key-value pairs, written in {}.
  • Array — an ordered list of values, written in [].

The values inside either can be any JSON type — including other objects and arrays. This is what makes JSON expressive enough for real-world data.

Pattern 1 — Object Inside an Object

{
  "user": {
    "name": "Anita",
    "address": {
      "city": "Mumbai",
      "country": "India"
    }
  }
}

To reach the city: user → address → city.

In JavaScript

const data = await response.json();
console.log(data.user.address.city);   // "Mumbai"

In Python

data = response.json()
print(data["user"]["address"]["city"])   # "Mumbai"

Pattern 2 — Array of Objects

{
  "users": [
    {"id": 1, "name": "Anita"},
    {"id": 2, "name": "Ravi"},
    {"id": 3, "name": "Mira"}
  ]
}

To get the second user's name: users → [1] → name.

In JavaScript

console.log(data.users[1].name);   // "Ravi"

// Loop over all users
data.users.forEach(u => console.log(u.id, u.name));

In Python

print(data["users"][1]["name"])   # "Ravi"

for u in data["users"]:
    print(u["id"], u["name"])

Pattern 3 — Deeply Nested Data

A realistic e-commerce order response:

{
  "order_id": 4521,
  "customer": {
    "name": "Anita",
    "email": "anita@example.com"
  },
  "items": [
    {
      "product_id": "P100",
      "name": "Wireless Mouse",
      "qty": 2,
      "price": 500,
      "discount": {"type": "percent", "value": 10}
    },
    {
      "product_id": "P200",
      "name": "Keyboard",
      "qty": 1,
      "price": 1500,
      "discount": null
    }
  ],
  "shipping": {
    "address": {
      "city": "Mumbai",
      "pin": "400001"
    },
    "method": "express",
    "cost": 100
  }
}

Reading it step by step

Question: "What is the discount on the first item?"

  1. Start at the root object.
  2. Go to items — that's an array.
  3. Take the first element items[0] — an object.
  4. Go to discount — an object.
  5. Go to value — a number, 10.

In JavaScript: data.items[0].discount.value
In Python: data["items"][0]["discount"]["value"]

Question: "List all product names in the order"

// JavaScript
data.items.map(item => item.name);
// ["Wireless Mouse", "Keyboard"]

# Python
[item["name"] for item in data["items"]]

Pattern 4 — Mixed Arrays

JSON arrays can hold mixed types:

{"values": [1, "two", true, null, [1, 2], {"k": "v"}]}

This is valid JSON but rare in real APIs. Most APIs use arrays of a single type (all objects, or all strings) for consistency.

Common Mistakes

  1. Assuming a nested key exists. data.user.address.city throws if address is null or undefined. Use optional chaining (data?.user?.address?.city in modern JS) or check each level.
  2. Forgetting array indices are zero-based. items[1] is the second item, not the first.
  3. Confusing arrays with objects. Arrays use [] access by index; objects use . or ["key"] access by key.
  4. Not handling null nested objects. If discount can be null (as in the second item above), check before accessing discount.value.
  5. Modifying JSON directly. JSON is text. You parse it into a native object, modify that, and then serialize back. You don't "edit JSON" — you edit the parsed structure.

Practical Exercise (10 minutes)

Use the e-commerce order JSON above. Write code (JavaScript or Python) to:

  1. Print the customer's email.
  2. Print the shipping city.
  3. Print the name of every product in the order.
  4. Calculate the total cost (sum of qty × price for each item, plus shipping cost).
  5. For each item with a discount, print the discount type and value.

Mini Challenge

Call the JSONPlaceholder API at https://jsonplaceholder.typicode.com/users. It returns an array of 10 user objects, each with nested address, company, and geo fields. Write code that prints each user's name, city, and company name.

Key Takeaways

  • Objects hold key-value pairs; arrays hold ordered lists. Both can nest inside each other.
  • Access nested values by chaining: data.user.address.city (JS) or data["user"]["address"]["city"] (Python).
  • Arrays use zero-based index access: items[0] is the first item.
  • Always check for null/undefined before accessing nested keys.
  • Real API responses are usually 3–5 levels deep. Practice reading them step by step.
Course continuity
Previously: Lesson 11 introduced JSON.
Today: You learned to navigate nested JSON — the skill you need for every real API.
Next: Lesson 13 practices reading complex responses from a real API.

FAQ

How deep can JSON nest?

No formal limit, but practical limits apply. Most APIs cap nesting at 5–7 levels. Deeply nested JSON is hard to read, hard to cache, and slow to parse. If your data needs 10+ levels, consider flattening it.

What is JSONPath?

JSONPath is a query language for JSON, similar to XPath for XML. It lets you write expressions like $.items[*].name to extract all item names. Useful for complex extractions, but most API testing uses direct property access in code.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments