{"record":{"id":"9d4629fb1713526e","repo":"sansan0/TrendRadar","slug":"date-range-json-e","errorCode":null,"errorMessage":"date_range JSON 解析失败: {e}","messagePattern":"date_range JSON 解析失败: (.+?)","errorType":"validation","errorClass":"InvalidParameterError","httpStatus":null,"severity":"error","filePath":"mcp_server/utils/validators.py","lineNumber":392,"sourceCode":"    Returns:\n        (start_date, end_date) 元组，或 None\n\n    Raises:\n        InvalidParameterError: 日期范围无效\n    \"\"\"\n    if date_range is None:\n        return None\n\n    # 支持字符串形式的输入\n    if isinstance(date_range, str):\n        stripped = date_range.strip()\n\n        # 1. 检查是否是 JSON 对象格式\n        if stripped.startswith('{') and stripped.endswith('}'):\n            try:\n                date_range = json.loads(stripped)\n            except json.JSONDecodeError as e:\n                raise InvalidParameterError(\n                    f\"date_range JSON 解析失败: {e}\",\n                    suggestion='请使用正确的JSON格式: {\"start\": \"YYYY-MM-DD\", \"end\": \"YYYY-MM-DD\"}'\n                )\n        # 2. 检查是否是单日字符串格式 YYYY-MM-DD\n        elif len(stripped) == 10 and stripped[4] == '-' and stripped[7] == '-':\n            try:\n                single_date = datetime.strptime(stripped, \"%Y-%m-%d\")\n                return (single_date, single_date)\n            except ValueError:\n                raise InvalidParameterError(\n                    f\"日期格式错误: {stripped}\",\n                    suggestion=\"请使用 YYYY-MM-DD 格式，例如: 2025-10-11\"\n                )\n        # 3. 尝试自然语言解析\n        else:\n            try:\n                result = DateParser.resolve_date_range_expression(stripped)\n                if result.get(\"success\"):","sourceCodeStart":374,"sourceCodeEnd":410,"githubUrl":"https://github.com/sansan0/TrendRadar/blob/8ee26026ba6c11dec41a95fb3895a7162876caa1/mcp_server/utils/validators.py#L374-L410","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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)"],"exampleFix":"# before\ndate_range = str({\"start\": \"2025-10-01\", \"end\": \"2025-10-11\"})  # {'start': '2025-10-01', ...}\n# after\nimport json\ndate_range = json.dumps({\"start\": \"2025-10-01\", \"end\": \"2025-10-11\"})\n# best: pass the dict itself","handlingStrategy":"validation","validationCode":"if (typeof dateRange === 'string' && dateRange.trim().startsWith('{')) {\n  try { dateRange = JSON.parse(dateRange); } catch { dateRange = undefined; }\n}\n// or build valid JSON: JSON.stringify({start, end})","typeGuard":"const isJsonObjectString = (s: string): boolean => {\n  try { return typeof JSON.parse(s) === 'object' && JSON.parse(s) !== null; } catch { return false; }\n};","tryCatchPattern":"try { call({ date_range: str }); }\ncatch (e) {\n  if (/JSON 解析失败/.test(e.message)) call({ date_range: { start, end } }); // send structured object instead\n  else throw e;\n}","preventionTips":["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"],"tags":["json","date-range","serialization","validation"],"backgroundTag":null,"analyzedSha":"8ee26026ba6c11dec41a95fb3895a7162876caa1","analyzedAt":"2026-08-15T01:42:18.084Z","schemaVersion":2},"datasetVersion":"2026-08-16T03:17:38.424Z"}