首页 » JavaScript » 正文

js 报错 Unexpected end of JSON input,Unexpected token u in JSON at position 0

2021-1-19 ·  3,650 views  ·  0 replies 

出现这种错误大概率是JSON.parse()函数传入的参数有问题,也就是不符合JSON规范,应该先排查这块,下面是详解

js 报错 Unexpected end of JSON input,Unexpected token u in JSON at position 0

JSON 通常用于与服务端交换数据。
在接收服务器数据时一般是字符串。
我们可以使用 JSON.parse() 方法将数据转换为 JavaScript 对象。

在谷歌浏览器的 Console 调试台中尝试一下这几种参数的返回结果:

JSON.parse(null);
// null

JSON.parse("");
// VM6600:1 Uncaught SyntaxError: Unexpected end of JSON input

JSON.parse(undefined);
// VM6635:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0

可以发现 JSON.parse() 的参数必须符合 JSON字符串 的格式才可以被正确的转换为对象,否则可能会引起报错,从而对其它的代码造成影响。

当我们不能确定服务端返回的数据类型时,这几个例子就可以用上了:

// 判断数据是否存在
var str = str && JSON.parse(str) || {};

// 判断数据类型
var str = typeof str == "string" ? JSON.parse(str) : {};

// 通过 try catch 捕捉异常,防止代码报错
var c = null;
try {
    c = JSON.parse(str)
} catch (d) {}

同理 JSON.stringify

var g = "";
try {
    g = JSON.stringify(a)
} catch (u) {}

"object" == typeof a ? JSON.stringify(a) : a

以上内容转载自:董先生的博客园

«上一篇: :下一篇»
  1. 还没有任何评论,你来说两句吧

Leave a reply