首页 > Web开发 > 详细

JSON.parse() 报错和一些解决方法

时间:2019-12-07 11:28:29      阅读:285      评论:0      收藏:0      [点我收藏+]

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.parse() 报错和一些解决方法

原文:https://www.cnblogs.com/sirdong/p/12000817.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!