Batu Lab NotesPractical developer guides

Validate a JSON list contains only objects

By Batu · English technical notes

Validate a JSON list contains only objects

To validate that a JSON list contains only objects, decode it and check every item with isinstance(item, dict) before calling dictionary methods. JSON decoding does not impose a schema: the array [{"id": 1}, 2, {"id": 3}] becomes a Python list containing two dictionaries and one integer.

The first loop intentionally represents a naive consumer. It calls .get("id") for every decoded item and fails when it reaches the integer, so the example prints a stable summary rather than interpreter-specific exception wording. require_objects is the correction. It enumerates the list, identifies the first non-object, and raises a contract-oriented error containing both its index and its Python type. The final output is therefore index 1 has type int. The assertion before the failing loop records the exact decoded shape, and the validator does not alter the list when every item passes.

Python’s JSON decoder conversion table specifies that JSON arrays decode to list and JSON objects decode to dict. This validation is an application-level rule layered on top of that conversion; it does not prove that accepted objects contain valid id values. The example is compatible with Python 3.6+.

AI assistance disclosure: this article was drafted with AI assistance and executes only a fixed in-memory JSON fixture.

import json

source = '[{"id": 1}, 2, {"id": 3}]'
items = json.loads(source)

assert items == [{"id": 1}, 2, {"id": 3}]
try:
    for item in items:
        item.get("id")
except AttributeError:
    print("naive consumer: fails on int")


def require_objects(values):
    for index, value in enumerate(values):
        if not isinstance(value, dict):
            raise ValueError(
                "index {} has type {}".format(index, type(value).__name__)
            )
    return values


try:
    require_objects(items)
except ValueError as error:
    print("validator:", error)
naive consumer: fails on int
validator: index 1 has type int