{"record":{"id":"98671d1331bc8d3d","repo":"SeleniumHQ/selenium","slug":"invalid-json-in-storage-state-file-file-path-e","errorCode":null,"errorMessage":"Invalid JSON in storage state file {file_path}: {e}","messagePattern":"Invalid JSON in storage state file (.+?): (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"py/selenium/webdriver/common/api_request_context.py","lineNumber":571,"sourceCode":"            base_url: Optional base URL for this context.\n            extra_headers: Optional headers for this context.\n            storage_state: Optional cookies to pre-load, as a dict, JSON file path, or Path.\n            fail_on_status_code: If True, raise APIRequestFailure for non-2xx responses.\n\n        Returns:\n            An _IsolatedAPIRequestContext instance.\n        \"\"\"\n        cookies: list[dict] = []\n        if storage_state is not None:\n            if isinstance(storage_state, (str, pathlib.Path)):\n                file_path = pathlib.Path(storage_state)\n                if not file_path.exists():\n                    raise FileNotFoundError(f\"Storage state file not found: {file_path}\")\n                try:\n                    with open(file_path) as f:\n                        state = json.load(f)\n                except json.JSONDecodeError as e:\n                    raise ValueError(f\"Invalid JSON in storage state file {file_path}: {e}\") from e\n                except OSError as e:\n                    raise OSError(f\"Cannot read storage state file {file_path}: {e}\") from e\n            else:\n                state = storage_state\n            cookies = list(state.get(\"cookies\", []))\n\n        return _IsolatedAPIRequestContext(\n            base_url=base_url,\n            extra_headers=extra_headers,\n            cookies=cookies,\n            timeout=self._timeout,\n            max_redirects=self._max_redirects,\n            fail_on_status_code=fail_on_status_code,\n        )\n\n    def get_storage_state(self, path: str | pathlib.Path | None = None) -> dict[str, Any]:\n        \"\"\"Export the current browser cookies as a storage state dict.\n","sourceCodeStart":553,"sourceCodeEnd":589,"githubUrl":"https://github.com/SeleniumHQ/selenium/blob/aa36b38e696a0909e973bdf5e2f9031ffe842c4b/py/selenium/webdriver/common/api_request_context.py#L553-L589","documentation":"When loading a storage-state file, if `json.load` raises `JSONDecodeError` (malformed JSON), Selenium re-raises it as `ValueError` with the file path and the underlying decode error. The storage-state file must be valid JSON with a top-level object, typically containing a `\"cookies\"` array.","triggerScenarios":"The file exists but contains invalid JSON (trailing comma, single quotes, truncated, HTML error page saved instead of JSON, an empty file, or a JSON5/CRLF-corrupted payload). E.g. a proxy returned an HTML 502 page that got saved as state.json.","commonSituations":"Manually edited JSON with a syntax error. File partially written / interrupted save. Wrong content downloaded into the file. Encoding issues (BOM, mixed encodings).","solutions":["Validate the file parses before passing it: `json.load(open(p))` in a scratch check.","Regenerate the file via `storage_state(path=...)` instead of hand-editing.","Run it through a JSON linter (e.g. `python -m json.tool state.json`).","Ensure the process that writes the file writes complete, valid JSON atomically."],"exampleFix":"// before\nctx = api.new_context(storage_state=\"state.json\")  # ValueError: Invalid JSON\n// after\nimport json\njson.load(open(\"state.json\"))  # fix until this succeeds, then:\nctx = api.new_context(storage_state=\"state.json\")","handlingStrategy":"validation","validationCode":"import json\nwith open(\"state.json\") as f:\n    json.load(f)  # raises early if invalid\nctx = api.new_context(storage_state=\"state.json\")","typeGuard":"import json\ndef is_valid_storage_state_json(path) -> bool:\n    try:\n        json.load(open(path)); return True\n    except Exception:\n        return False","tryCatchPattern":"try:\n    ctx = api.new_context(storage_state=path)\nexcept ValueError:\n    ctx = api.new_context(storage_state={\"cookies\": []})  # discard corrupt file","preventionTips":["Validate with python -m json.tool before loading.","Regenerate the file programmatically instead of hand-editing.","Write JSON atomically to avoid truncated files."],"tags":["storage-state","json","api-request","validation"],"backgroundTag":null,"analyzedSha":"aa36b38e696a0909e973bdf5e2f9031ffe842c4b","analyzedAt":"2026-08-14T02:32:32.244Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}