pola-rs/polars · error · TypeError

`Expr.str.json_decode` needs an explicitly given `dtype`…

Error message

`Expr.str.json_decode` needs an explicitly given `dtype` otherwise Polars is not able to determine the output type. If you want to eagerly infer datatype you can use `Series.str.json_decode`.

What it means

Expr.str.json_decode() cannot infer the JSON schema lazily inside an expression, so `dtype` is mandatory; omitting it raises this TypeError. The message points out that eager type inference is only available via Series.str.json_decode. This keeps the expression's output dtype well-defined at build time.

Solutions

  1. Provide an explicit dtype, e.g. strptime-style: pl.col('j').str.json_decode(pl.Struct({'a': pl.Int64})).
  2. For simple payloads use a scalar dtype: str.json_decode(pl.List(pl.Float64)).
  3. If you need inference, materialize a Series first: s.str.json_decode() (Series API) and inspect its dtype.
  4. If dtype comes from a variable, initialize it instead of leaving it None.

Example fix

// before
pl.col('json').str.json_decode()
// after
pl.col('json').str.json_decode(pl.Struct({'a': pl.Int64, 'b': pl.Boolean}))
Defensive patterns

Strategy: validation

Validate before calling

if dtype is None:
    raise ValueError('Expr.str.json_decode requires an explicit dtype')

Type guard

def has_dtype(dtype) -> bool:
    return isinstance(dtype, (pl.DataType, type)) and dtype is not None

Try / catch

try:
    expr = pl.col('j').str.json_decode(dtype)
except TypeError:
    expr = pl.col('j').str.json_decode(pl.String)

Prevention

When it happens

Trigger: Calling df.select(pl.col('json').str.json_decode()) with no dtype argument, or dtype=None from an unset variable.

Common situations: Porting Series-level code (where dtype is optional) to an expression context; forgetting dtype when refactoring json_path_match to json_decode; building expressions dynamically and leaving the dtype parameter out.

Understand the failure class

Background: "missing required argument" and "the following required arguments were not provided": what required-argument errors mean and how to fix them — this error's family across 20 libraries.

Related errors


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

Appendix: source

Thrown at py-polars/src/polars/expr/string.py:1343

        >>> df = pl.DataFrame(
        ...     {"json": ['{"a":1, "b": true}', None, '{"a":2, "b": false}']}
        ... )
        >>> dtype = pl.Struct([pl.Field("a", pl.Int64), pl.Field("b", pl.Boolean)])
        >>> df.with_columns(decoded=pl.col("json").str.json_decode(dtype))
        shape: (3, 2)
        ┌─────────────────────┬───────────┐
        │ json                ┆ decoded   │
        │ ---                 ┆ ---       │
        │ str                 ┆ struct[2] │
        ╞═════════════════════╪═══════════╡
        │ {"a":1, "b": true}  ┆ {1,true}  │
        │ null                ┆ null      │
        │ {"a":2, "b": false} ┆ {2,false} │
        └─────────────────────┴───────────┘
        """
        if dtype is None:
            msg = "`Expr.str.json_decode` needs an explicitly given `dtype` otherwise Polars is not able to determine the output type. If you want to eagerly infer datatype you can use `Series.str.json_decode`."
            raise TypeError(msg)

        dtype_expr = parse_into_datatype_expr(dtype)._pydatatype_expr
        return wrap_expr(self._pyexpr.str_json_decode(dtype_expr))

    def json_path_match(self, json_path: IntoExprColumn) -> Expr:
        """
        Extract the first match from a JSON string using the provided JSONPath.

        Throws errors if invalid JSON strings are encountered. All return values
        are cast to :class:`String`, regardless of the original value.

        Documentation on the JSONPath standard can be found
        `here <https://goessner.net/articles/JsonPath/>`_.

        .. engine-support:: in-memory, streaming, distributed

        Parameters
        ----------

View on GitHub (pinned to fe841f959e)