sansan0/TrendRadar · error · InvalidParameterError

date_range JSON 解析失败: {e}

Error message

date_range JSON 解析失败: {e}

What it means

Raised by normalize_date_range when the input string starts with '{' and ends with '}' (so it looks like a JSON object) but json.loads raises. The suggestion shows the expected shape {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}. Typical causes: single quotes instead of double quotes, trailing commas, unquoted keys, or a truncated payload.

Source

Thrown at mcp_server/utils/validators.py:392

    Returns:
        (start_date, end_date) 元组,或 None

    Raises:
        InvalidParameterError: 日期范围无效
    """
    if date_range is None:
        return None

    # 支持字符串形式的输入
    if isinstance(date_range, str):
        stripped = date_range.strip()

        # 1. 检查是否是 JSON 对象格式
        if stripped.startswith('{') and stripped.endswith('}'):
            try:
                date_range = json.loads(stripped)
            except json.JSONDecodeError as e:
                raise InvalidParameterError(
                    f"date_range JSON 解析失败: {e}",
                    suggestion='请使用正确的JSON格式: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}'
                )
        # 2. 检查是否是单日字符串格式 YYYY-MM-DD
        elif len(stripped) == 10 and stripped[4] == '-' and stripped[7] == '-':
            try:
                single_date = datetime.strptime(stripped, "%Y-%m-%d")
                return (single_date, single_date)
            except ValueError:
                raise InvalidParameterError(
                    f"日期格式错误: {stripped}",
                    suggestion="请使用 YYYY-MM-DD 格式,例如: 2025-10-11"
                )
        # 3. 尝试自然语言解析
        else:
            try:
                result = DateParser.resolve_date_range_expression(stripped)
                if result.get("success"):

View on GitHub (pinned to 8ee26026ba)

Solutions

  1. Use valid JSON with double-quoted keys and values: {"start": "2025-10-01", "end": "2025-10-11"}
  2. Prefer sending a real JSON object (not a string) — most MCP transports preserve structure, avoiding quoting bugs entirely
  3. Validate with JSON.parse/json.loads client-side before sending
  4. When building from a Python dict, use json.dumps(d), never str(d)

Example fix

# before
date_range = str({"start": "2025-10-01", "end": "2025-10-11"})  # {'start': '2025-10-01', ...}
# after
import json
date_range = json.dumps({"start": "2025-10-01", "end": "2025-10-11"})
# best: pass the dict itself
Defensive patterns

Strategy: validation

Validate before calling

if (typeof dateRange === 'string' && dateRange.trim().startsWith('{')) {
  try { dateRange = JSON.parse(dateRange); } catch { dateRange = undefined; }
}
// or build valid JSON: JSON.stringify({start, end})

Type guard

const isJsonObjectString = (s: string): boolean => {
  try { return typeof JSON.parse(s) === 'object' && JSON.parse(s) !== null; } catch { return false; }
};

Try / catch

try { call({ date_range: str }); }
catch (e) {
  if (/JSON 解析失败/.test(e.message)) call({ date_range: { start, end } }); // send structured object instead
  else throw e;
}

Prevention

When it happens

Trigger: Sending date_range as "{start: '2025-10-01', end: '2025-10-11'}" (Python-style dict repr or JS object literal) instead of valid JSON. Also double-serialization artifacts like '{{...}}' or escaped-quote corruption from shell/JSON double-encoding.

Common situations: LLM clients emitting Python repr instead of JSON; users copy-pasting dict literals from Python tutorials; string concatenation building malformed JSON; curl on shells mangling quotes.

Related errors


AI-assisted analysis of sansan0/TrendRadar@8ee26026ba (2026-08-15). Data as JSON: /api/errors/9d4629fb1713526e. Report an issue: GitHub.