Python
JSON
key existence
iteration
programming

Check if key exists and iterate the JSON array using Python

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

When reading JSON in Python, safe code usually does two things before iterating deeply: it checks whether a key exists and it verifies that the value has the shape you expect. That matters because real payloads often contain optional keys, missing fields, or values of the wrong type.

Parse the JSON First

Start by deserializing the raw JSON string into Python objects.

python
1import json
2
3raw = '{"users": [{"id": 1, "name": "Ava"}], "meta": {"source": "api"}}'
4data = json.loads(raw)
5
6print(type(data))

For a normal JSON object, data is a Python dict.

Check Whether a Key Exists

Use direct membership tests for required keys and get for optional ones.

python
1if "users" not in data:
2    raise ValueError("missing required key: users")
3
4users = data.get("users", [])

That distinction is useful:

  • required fields should fail loudly when absent,
  • optional fields often deserve a default value.

Validate the Value Before Iterating

Key existence alone is not enough. The value might exist but be the wrong type.

python
users = data.get("users", [])
if not isinstance(users, list):
    raise TypeError("users must be a list")

That small check prevents confusing runtime errors later when the code assumes list behavior.

Iterate the Array Safely

Once the value is confirmed to be a list, iterate through it and validate each element if necessary.

python
1for index, user in enumerate(users):
2    if not isinstance(user, dict):
3        print(f"skip item {index}: expected object")
4        continue
5
6    user_id = user.get("id")
7    name = user.get("name", "unknown")
8    print(index, user_id, name)

This pattern is robust when consuming external JSON because one malformed element does not have to crash the whole loop.

Handle Nested Arrays the Same Way

For nested arrays, repeat the same pattern: check the branch, validate the type, then iterate.

python
1events = data.get("events", [])
2if isinstance(events, list):
3    for event in events:
4        if not isinstance(event, dict):
5            continue
6
7        tags = event.get("tags", [])
8        if isinstance(tags, list):
9            for tag in tags:
10                print("tag", tag)

The shape-checking logic stays the same even when the structure gets deeper.

Boundary Validation Makes the Rest of the Code Simpler

In larger programs, this kind of defensive parsing often grows into schema validation or model parsing. Even if you stay with plain dictionaries and lists, the same principle still applies: validate near the boundary so the rest of the code can trust a cleaner internal contract.

That makes malformed input boring instead of dangerous.

Choose Between Strict and Tolerant Parsing

Not every JSON consumer should behave the same way.

Strict parsing is appropriate when:

  • missing keys indicate a broken upstream contract,
  • wrong types should stop processing immediately,
  • correctness matters more than partial success.

Tolerant parsing is appropriate when:

  • payloads come from many uncontrolled sources,
  • partial data is still useful,
  • the program should skip bad items and continue.

The syntax for checking keys is the same, but the error-handling policy changes the structure of the loop.

Common Pitfalls

A common mistake is assuming a key exists just because one example payload contained it.

Another issue is checking key existence but never validating the type of the associated value.

Developers also often mix parsing, validation, mutation, and business logic in one loop, which quickly becomes hard to read and hard to debug.

Summary

  • Parse JSON into Python objects with json.loads.
  • Use in for required keys and get for optional keys.
  • Validate that the value is actually a list before iterating.
  • Guard each element when consuming untrusted or external payloads.
  • Repeat the same key-check and type-check pattern for nested arrays.

Course illustration
Course illustration

All Rights Reserved.