FoundationAgents/MetaGPT · error · FileNotFoundError

json_file: {json_file} not exist, return []

Error message

json_file: {json_file} not exist, return []

What it means

read_json_file in metagpt/utils/common.py checks Path(json_file).exists() first and raises FileNotFoundError when the path is missing. Note the message text says 'return []' but the function actually raises — the message is a leftover from an older returning-default behavior.

Source

Thrown at metagpt/utils/common.py:574

        if retry_state.fn is None:
            fn_name = "<unknown>"
        else:
            # Retrieve the callable's name using a utility function
            fn_name = _utils.get_callback_name(retry_state.fn)

        # Log an error message with the function name, time since start, attempt number, and the exception
        i.error(
            f"Finished call to '{fn_name}' after {sec_format % retry_state.seconds_since_start}(s), "
            f"this was the {_utils.to_ordinal(retry_state.attempt_number)} time calling it. "
            f"exp: {retry_state.outcome.exception()}"
        )

    return log_it


def read_json_file(json_file: str, encoding: str = "utf-8") -> list[Any]:
    if not Path(json_file).exists():
        raise FileNotFoundError(f"json_file: {json_file} not exist, return []")

    with open(json_file, "r", encoding=encoding) as fin:
        try:
            data = json.load(fin)
        except Exception:
            raise ValueError(f"read json file: {json_file} failed")
    return data


def handle_unknown_serialization(x: Any) -> str:
    """For `to_jsonable_python` debug, get more detail about the x."""

    if inspect.ismethod(x):
        tip = f"Cannot serialize method '{x.__func__.__name__}' of class '{x.__self__.__class__.__name__}'"
    elif inspect.isfunction(x):
        tip = f"Cannot serialize function '{x.__name__}'"
    elif hasattr(x, "__class__"):
        tip = f"Cannot serialize instance of '{x.__class__.__name__}'"

View on GitHub (pinned to 11cdf466d0)

Solutions

  1. Verify the path: print Path(json_file).resolve() and check it exists.
  2. Use absolute paths or anchor relative paths to the project root (__file__ or CONFIG_PATH).
  3. Ensure the upstream step that writes the JSON ran successfully.
  4. If a missing file is a normal case, guard with Path(json_file).exists() and supply a default yourself.

Example fix

# before
data = read_json_file('configs/settings.json')  # cwd-dependent, may raise

# after
from pathlib import Path
p = Path(__file__).parent / 'configs' / 'settings.json'
data = read_json_file(str(p)) if p.exists() else []
Defensive patterns

Strategy: validation

Validate before calling

from pathlib import Path

def json_readable(json_file: str) -> bool:
    return Path(json_file).is_file()

Try / catch

try:
    data = read_json_file(path)
except FileNotFoundError:
    data = []  # or raise a domain-specific error with context

Prevention

When it happens

Trigger: read_json_file('data/config.json') when the file was never created; relative path resolved against a different working directory; typo in the filename; file expected to be generated by an earlier pipeline stage that silently skipped it.

Common situations: Workspace-relative paths under pytest or a daemon where cwd differs; downloading/scaffolding step that should have produced the JSON failed; case-sensitive filename mismatch on Linux.

Related errors


AI-assisted analysis of FoundationAgents/MetaGPT@11cdf466d0 (2026-08-14). Data as JSON: /api/errors/189720000d81f77e. Report an issue: GitHub.