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
- Use valid JSON with double-quoted keys and values: {"start": "2025-10-01", "end": "2025-10-11"}
- Prefer sending a real JSON object (not a string) — most MCP transports preserve structure, avoiding quoting bugs entirely
- Validate with JSON.parse/json.loads client-side before sending
- 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
- Send structured objects; only stringify when the transport forces strings
- Never use Python str(dict) or JS String(obj) — use json.dumps/JSON.stringify
- JSON.parse-validate outbound JSON strings in tests
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
- 日期表达式不能为空
- limit 参数必须是整数类型
- 无法识别的日期表达式: {stripped}
- date_range 必须是字典类型、日期字符串或有效的JSON字符串
- date_range 必须包含 start 和 end 字段
AI-assisted analysis of sansan0/TrendRadar@8ee26026ba (2026-08-15).
Data as JSON: /api/errors/9d4629fb1713526e.
Report an issue: GitHub.