pola-rs/polars · error

expected list or dict of objects

Error message

expected list or dict of objects

What it means

`pl.json_normalize` flattens semi-structured JSON records into a DataFrame. This ValueError is raised when `data` is neither a dict (single record), a Mapping, nor an Iterable of such objects (and not a string).

Solutions

  1. Ensure `data` is a list of dicts or a single dict; wrap a single record as `[record]` only if it is a Mapping (a bare Mapping is already accepted).
  2. Parse JSON strings first: `pl.json_normalize(json.loads(text))` or use `pl.read_json`.
  3. Guard with `isinstance(data, (dict, list))` and an informative fallback before calling.

Example fix

// before
pl.json_normalize(response_text)  # str
// after
import json
pl.json_normalize(json.loads(response_text))
Defensive patterns

Strategy: validation

Validate before calling

if data is None or isinstance(data, (str, int, float)):
    raise ValueError('json_normalize needs a list of dicts or a single dict')

Type guard

def is_records(x) -> bool:
    from collections.abc import Mapping
    return isinstance(x, Mapping) or (isinstance(x, list) and all(isinstance(i, Mapping) for i in x))

Try / catch

try:
    df = pl.json_normalize(data)
except ValueError:
    df = pl.DataFrame()  # or log and skip empty/invalid payload

Prevention

When it happens

Trigger: Calling `pl.json_normalize(data)` with `data=None`, a scalar (int/str), a generator of non-dict items already consumed, or any non-iterable object.

Common situations: API call returned None or a scalar (error payload) instead of a list of records; accidentally passing a JSON string (use `pl.read_json` or `json.loads` first); passing a single dict wrapped wrong — single dicts are accepted, but scalars are not.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/39139d10e804bb07. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/convert/normalize.py:246

    ╞══════╪════════════╪═══════════════════════════════╡
    │ 1    ┆ Cole Volk  ┆ b"{"height":180,"weight":85}" │
    │ 2    ┆ Faye Raker ┆ b"{"height":155,"weight":58}" │
    │ null ┆ Mark Reg   ┆ b"{"height":170,"weight":78}" │
    └──────┴────────────┴───────────────────────────────┘
    """
    if max_level is None:
        max_level = 1 << 32  # eg: u32
    max_level += 1

    if isinstance(data, Sequence) and len(data) == 0:
        return DataFrame(schema=schema)
    elif isinstance(data, Mapping):
        data = [data]
    elif isinstance(data, Iterable) and not isinstance(data, str):  # type: ignore[redundant-expr]
        data = list(data)
    else:
        msg = "expected list or dict of objects"
        raise ValueError(msg)

    if encoder is None:
        encoder = json.dumps

    return DataFrame(
        _simple_json_normalize(
            data,
            separator=separator,
            max_level=max_level,
            encoder=encoder,
        ),
        schema=schema,
        strict=strict,
        infer_schema_length=infer_schema_length,
    )

View on GitHub (pinned to fe841f959e)