SeleniumHQ/selenium · error · ValueError
Invalid JSON in storage state file {file_path}: {e}
Error message
Invalid JSON in storage state file {file_path}: {e} What it means
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.
Source
Thrown at py/selenium/webdriver/common/api_request_context.py:571
base_url: Optional base URL for this context.
extra_headers: Optional headers for this context.
storage_state: Optional cookies to pre-load, as a dict, JSON file path, or Path.
fail_on_status_code: If True, raise APIRequestFailure for non-2xx responses.
Returns:
An _IsolatedAPIRequestContext instance.
"""
cookies: list[dict] = []
if storage_state is not None:
if isinstance(storage_state, (str, pathlib.Path)):
file_path = pathlib.Path(storage_state)
if not file_path.exists():
raise FileNotFoundError(f"Storage state file not found: {file_path}")
try:
with open(file_path) as f:
state = json.load(f)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON in storage state file {file_path}: {e}") from e
except OSError as e:
raise OSError(f"Cannot read storage state file {file_path}: {e}") from e
else:
state = storage_state
cookies = list(state.get("cookies", []))
return _IsolatedAPIRequestContext(
base_url=base_url,
extra_headers=extra_headers,
cookies=cookies,
timeout=self._timeout,
max_redirects=self._max_redirects,
fail_on_status_code=fail_on_status_code,
)
def get_storage_state(self, path: str | pathlib.Path | None = None) -> dict[str, Any]:
"""Export the current browser cookies as a storage state dict.
View on GitHub (pinned to aa36b38e69)
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.
Example fix
// before
ctx = api.new_context(storage_state="state.json") # ValueError: Invalid JSON
// after
import json
json.load(open("state.json")) # fix until this succeeds, then:
ctx = api.new_context(storage_state="state.json") Defensive patterns
Strategy: validation
Validate before calling
import json
with open("state.json") as f:
json.load(f) # raises early if invalid
ctx = api.new_context(storage_state="state.json") Type guard
import json
def is_valid_storage_state_json(path) -> bool:
try:
json.load(open(path)); return True
except Exception:
return False Try / catch
try:
ctx = api.new_context(storage_state=path)
except ValueError:
ctx = api.new_context(storage_state={"cookies": []}) # discard corrupt file Prevention
- Validate with python -m json.tool before loading.
- Regenerate the file programmatically instead of hand-editing.
- Write JSON atomically to avoid truncated files.
When it happens
Trigger: 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.
Common situations: Manually edited JSON with a syntax error. File partially written / interrupted save. Wrong content downloaded into the file. Encoding issues (BOM, mixed encodings).
Understand the failure class
- Parsing and encoding errors: unexpected token, malformed input — why parsers reject input and how to find the real culprit.
Related errors
- Storage state file not found: {file_path}
- Cannot read storage state file {file_path}: {e}
- Cannot write storage state to {file_path}: {e}
- Unexpected compiled output format. Expected it to start with
- Unexpected compiled output format. Expected it to start with
AI-assisted analysis of SeleniumHQ/selenium@aa36b38e69 (2026-08-14).
Data as JSON: /api/errors/98671d1331bc8d3d.
Report an issue: GitHub.