{"record":{"id":"2d6c9f19872e4782","repo":"pola-rs/polars","slug":"expr-str-json-decode-needs-an-explicitly-given","errorCode":null,"errorMessage":"`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`.","messagePattern":"`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`\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/expr/string.py","lineNumber":1343,"sourceCode":"        >>> df = pl.DataFrame(\n        ...     {\"json\": ['{\"a\":1, \"b\": true}', None, '{\"a\":2, \"b\": false}']}\n        ... )\n        >>> dtype = pl.Struct([pl.Field(\"a\", pl.Int64), pl.Field(\"b\", pl.Boolean)])\n        >>> df.with_columns(decoded=pl.col(\"json\").str.json_decode(dtype))\n        shape: (3, 2)\n        ┌─────────────────────┬───────────┐\n        │ json                ┆ decoded   │\n        │ ---                 ┆ ---       │\n        │ str                 ┆ struct[2] │\n        ╞═════════════════════╪═══════════╡\n        │ {\"a\":1, \"b\": true}  ┆ {1,true}  │\n        │ null                ┆ null      │\n        │ {\"a\":2, \"b\": false} ┆ {2,false} │\n        └─────────────────────┴───────────┘\n        \"\"\"\n        if dtype is None:\n            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`.\"\n            raise TypeError(msg)\n\n        dtype_expr = parse_into_datatype_expr(dtype)._pydatatype_expr\n        return wrap_expr(self._pyexpr.str_json_decode(dtype_expr))\n\n    def json_path_match(self, json_path: IntoExprColumn) -> Expr:\n        \"\"\"\n        Extract the first match from a JSON string using the provided JSONPath.\n\n        Throws errors if invalid JSON strings are encountered. All return values\n        are cast to :class:`String`, regardless of the original value.\n\n        Documentation on the JSONPath standard can be found\n        `here <https://goessner.net/articles/JsonPath/>`_.\n\n        .. engine-support:: in-memory, streaming, distributed\n\n        Parameters\n        ----------","sourceCodeStart":1325,"sourceCodeEnd":1361,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/expr/string.py#L1325-L1361","documentation":"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.","triggerScenarios":"Calling df.select(pl.col('json').str.json_decode()) with no dtype argument, or dtype=None from an unset variable.","commonSituations":"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.","solutions":["Provide an explicit dtype, e.g. strptime-style: pl.col('j').str.json_decode(pl.Struct({'a': pl.Int64})).","For simple payloads use a scalar dtype: str.json_decode(pl.List(pl.Float64)).","If you need inference, materialize a Series first: s.str.json_decode() (Series API) and inspect its dtype.","If dtype comes from a variable, initialize it instead of leaving it None."],"exampleFix":"// before\npl.col('json').str.json_decode()\n// after\npl.col('json').str.json_decode(pl.Struct({'a': pl.Int64, 'b': pl.Boolean}))","handlingStrategy":"validation","validationCode":"if dtype is None:\n    raise ValueError('Expr.str.json_decode requires an explicit dtype')","typeGuard":"def has_dtype(dtype) -> bool:\n    return isinstance(dtype, (pl.DataType, type)) and dtype is not None","tryCatchPattern":"try:\n    expr = pl.col('j').str.json_decode(dtype)\nexcept TypeError:\n    expr = pl.col('j').str.json_decode(pl.String)","preventionTips":["Always supply dtype with Expr.str.json_decode; it is mandatory.","Use Series.str.json_decode when you want eager type inference.","Define struct dtypes alongside the JSON schema you expect."],"tags":["python","polars","type-error","missing-argument","json"],"backgroundTag":"missing-required-argument","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}