{"record":{"id":"5548476082ee6d11","repo":"pathwaycom/pathway","slug":"cannot-convert-json-self-value-to-type","errorCode":null,"errorMessage":"Cannot convert Json {self.value} to {type}","messagePattern":"Cannot convert Json (.+?) to (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/pathway/internals/json.py","lineNumber":245,"sourceCode":"        ...     data: pw.Json\n        ...\n        >>> @pw.udf\n        ... def extract(data: pw.Json) -> tuple:\n        ...     return tuple(data[\"value\"].as_dict().values())\n        ...\n        >>> table = pw.debug.table_from_rows(schema=InputSchema, rows=[({\"value\": {\"inner\": 42}},)])\n        >>> result = table.select(result=extract(pw.this.data))\n        >>> pw.debug.compute_and_print(result, include_id=False)\n        result\n        (42,)\n        \"\"\"\n        return self._as_type(dict)\n\n    def _as_type(self, type: type[J]) -> Any:\n        if isinstance(self.value, type):\n            return self.value\n        else:\n            raise ValueError(f\"Cannot convert Json {self.value} to {type}\")\n\n\nJsonValue = (\n    int | float | str | bool | list[\"JsonValue\"] | dict[str, \"JsonValue\"] | None | Json\n)\n\nJ = TypeVar(\"J\", bound=JsonValue)\n\nJson.NULL = Json(None)\n\n__all__ = [\"Json\", \"JsonValue\"]\n","sourceCodeStart":227,"sourceCodeEnd":257,"githubUrl":"https://github.com/pathwaycom/pathway/blob/fa2f74a4649b7c5908690cf60137263d8d80de5f/python/pathway/internals/json.py#L227-L257","documentation":"Pathway's Json wrapper stores a value parsed from JSON; conversion helpers such as as_int()/as_str()/as_dict() call _as_type, which only succeeds when the wrapped Python value is already an instance of the requested type. If the JSON value has a different shape (e.g. you call as_int() on a string or as_dict() on a list), Python's isinstance check fails and this ValueError is raised. The error message embeds the actual value so you can see the mismatch.","triggerScenarios":"Calling Json.as_int(), as_float(), as_str(), as_bool(), as_list() or as_dict() (all delegate to _as_type at json.py:245) on a Json value whose underlying Python type does not match — e.g. pw.Json(\"42\").as_int(), or as_dict() on a JSON array [1,2]. Typically inside table.select(...) after io.www read or json parsing.","commonSituations":"REST APIs returning numbers as strings, JSON fields whose type varies between records (one has {\"a\": {...}}, next has {\"a\": 3}), or using as_list() on a dict / as_dict() on a list after an API contract change.","solutions":["Check the actual type first: use isinstance(pw_json.value, dict) or match on the value before calling as_*().","Use the untyped accessor: Json.value gives you the raw Python object; index it with ['key'] / iterate it directly instead of converting.","Normalize the source data (e.g. cast string digits with int(...) in a lambda) before wrapping in Json, or use pw.Json.convert with a converter that handles multiple shapes.","For numbers that may arrive as strings, write json.as_str() then int()/float() conversion in the expression."],"exampleFix":"// before\nresult = table.select(value=pw.this.data.as_int())  # data is Json(\"42\")\n\n// after\nresult = table.select(value=pw.this.data.as_int() if isinstance(pw.this.data.value, int) else int(pw.this.data.as_str()))","handlingStrategy":"type-guard","validationCode":"from pathway import Json\n\ndef json_type_ok(j: Json, target: type) -> bool:\n    return isinstance(j.value, target)","typeGuard":"from pathway import Json\nfrom typing import TypeGuard\n\ndef json_is_dict(j: Json) -> TypeGuard[Json]:\n    return isinstance(j.value, dict)\n\ndef json_is_int(j: Json) -> bool:\n    return isinstance(j.value, int) and not isinstance(j.value, bool)","tryCatchPattern":"try:\n    v = pw_json.as_int()\nexcept ValueError:\n    v = int(pw_json.as_str())  # or log and skip the row","preventionTips":["Inspect one raw record (pw_json.value) from each new source before writing as_*() calls.","Prefer pattern matching on type(j.value) in a lambda/select when API responses are polymorphic."],"tags":["json","type-conversion","runtime","pathway"],"backgroundTag":null,"analyzedSha":"fa2f74a4649b7c5908690cf60137263d8d80de5f","analyzedAt":"2026-08-15T01:48:17.006Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}