JavaScript 中 Unexpected end of JSON input 错误
尝试使用 JSON.parse
或 $.parseJSON
方法解析无效的 JSON 时,会发生“Unexpected end of JSON input”错误。 尝试解析空数组或字符串等值会导致错误。 要解决此错误,请在解析之前确保 JSON 有效。
请注意
,截图显示了发生错误的行。 在示例中,错误发生在第 2 行的 index.js 文件中。
// ⛔️ Uncaught SyntaxError: Unexpected end of JSON input
console.log(JSON.parse([]));
// ⛔️ Uncaught SyntaxError: Unexpected end of JSON input
console.log(JSON.parse(''));
我们将一个空数组和一个空字符串传递给 JSON.parse
方法并得到错误。 如果您使用 $.parseJSON
方法,结果也是一样的。
// ⛔️ Uncaught SyntaxError: Unexpected end of JSON input
console.log($.parseJSON(''));
我们收到错误是因为我们正在尝试解析无效的 JSON。
如果我们尝试解析来自服务器的空响应,或者当我们的服务器未随响应发送正确的 CORS 标头时,也会发生该错误。
如果我们的服务器发送一个空响应,而我们尝试对其进行 JSON.parse
,我们将收到错误消息。 在这种情况下,应该删除解析逻辑。
如果我们从服务器获取值,请确保服务器将 Content-Type
标头设置为 application/json。
我们可以通过以下3种方式解决“Unexpected end of JSON input”错误:
-
将我们的解析逻辑包装在
try/catch
块中 - 确保从我们的服务器返回有效的 JSON 响应
- 如果我们期待一个空的服务器响应,请从我们的代码中删除解析逻辑
我们可以通过打开开发人员工具并单击“网络”选项卡来检查服务器的响应。 如果单击 Response 选项卡,将看到服务器的响应。
下面是一个示例,说明如何使用 try/catch
块来避免在解析时出现“Unexpected end of input”错误。
try {
const result = JSON.parse('');
console.log(result);
} catch (err) {
// 👇️ SyntaxError: Unexpected end of JSON input
console.log('error', err);
}
如果 JSON.parse
方法由于解析无效的 JSON 而抛出错误,该错误将作为参数传递给我们可以处理的 catch 方法。
或者,如果我们知道服务器的响应不包含有效的 JSON,则可以删除对 JSON.parse
方法的调用。
我们还可以使用在线 JSON 验证器来检查 JSON 字符串是否有效。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。