迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中 Unexpected end of JSON input 错误

作者:迹忆客 最近更新:2022/11/28 浏览次数:

尝试使用 JSON.parse$.parseJSON 方法解析无效的 JSON 时,会发生“Unexpected end of JSON input”错误。 尝试解析空数组或字符串等值会导致错误。 要解决此错误,请在解析之前确保 JSON 有效。

JavaScript 中 Unexpected end of JSON input 错误

请注意 ,截图显示了发生错误的行。 在示例中,错误发生在第 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 选项卡,将看到服务器的响应。

javascript 检查服务器的响应

下面是一个示例,说明如何使用 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 字符串是否有效。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便