Convert JSON Arrays to Python List Type Annotations
Learn how to convert JSON arrays into Python list[T] type annotations. Covers lists of primitives, lists of objects, and nested list structures.
Detailed Explanation
JSON Arrays to Python Lists
JSON arrays map to Python's list type. The element type is inferred from the array contents — strings become list[str], objects become list[SomeClass].
Primitive Arrays
{
"tags": ["python", "json", "api"],
"scores": [95, 87, 92],
"weights": [0.5, 0.3, 0.2]
}
from dataclasses import dataclass
@dataclass
class Data:
tags: list[str]
scores: list[int]
weights: list[float]
Object Arrays
{
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
}
@dataclass
class User:
id: int
name: str
@dataclass
class Root:
users: list[User]
Empty Arrays
An empty JSON array [] is ambiguous — the converter cannot determine the element type. Most converters default to list[Any]. Once you know the expected type, update it manually:
from typing import Any
items: list[Any] # converter default
items: list[str] # manual fix after reviewing API docs
Nested Arrays
Arrays of arrays (e.g., a matrix [[1,2],[3,4]]) become nested list types:
matrix: list[list[int]]
Type Syntax Versions
| Python version | Syntax |
|---|---|
| 3.7-3.8 | List[str] (from typing) |
| 3.9+ | list[str] (built-in) |
The converter targets Python 3.9+ syntax by default, using lowercase list, dict, tuple, and set directly.
Iterating Typed Lists
for user in data.users:
print(user.name) # IDE knows user is User, provides autocompletion
Type-annotated lists give you proper autocompletion inside loops, comprehensions, and map/filter chains.
Use Case
You are consuming a paginated API that returns arrays of user objects and need Python type annotations so mypy validates your list comprehensions and loop variables.
Try It — JSON to Python Converter
Related Topics
Convert Simple JSON to a Python Dataclass
Dataclasses
Convert Nested JSON Objects to Python Dataclasses
Dataclasses
Convert Dynamic-Key JSON Objects to Python Dict Types
Type Annotations
Handle Optional and Nullable JSON Fields in Python
Type Annotations
Convert REST API Response JSON to Python Classes
Advanced Patterns