JSON.parse报错 Unexpect non-whiltespace character after JSON at position 4 at JSON.parse
时间: 2025-01-07 09:04:49 浏览: 169
解决 JSON.parse 报错 'Unexpected non-whitespace character after JSON at position 4'
当遇到 JSON.parse
出现 'Unexpected non-whitespace character after JSON at position 4'
错误时,通常意味着解析的字符串不是有效的 JSON 格式。具体来说,在位置 4 处存在意外字符[^1]。
为了排查此问题:
验证输入字符串:确保传递给
JSON.parse()
的字符串确实是有效 JSON 字符串。任何额外字符或不匹配的大括号都会导致错误。去除多余字符:如果原始响应包含除 JSON 数据外的内容,则需先清理这些附加部分再尝试解析[^2]。
下面是一个简单的调试方法来定位并修正该类错误:
try {
const jsonString = '{"key": "value"}'; // 假设这是从服务器获取的数据
console.log('Original String:', jsonString);
// 尝试解析前打印出来查看结构是否正确
console.log(JSON.stringify(jsonString, null, 2));
let parsedData;
try {
parsedData = JSON.parse(jsonString);
} catch (error) {
console.error('Error parsing JSON:', error.message);
// 如果失败了,可以试着去掉可能存在的 BOM 或其他不可见字符
const cleanedJsonString = jsonString.trim();
parsedData = JSON.parse(cleanedJsonString);
}
console.log('Parsed Data:', parsedData);
} catch (e) {
console.error(e);
}
这段代码展示了如何安全地处理潜在异常情况下的 JSON 解析操作,并提供了基本的日志记录以便于诊断问题所在。
相关推荐


















