其他分享
首页 > 其他分享> > 前端开发:报错Error in created hook:”SyntaxError:Unexpected token u in JSON at position 0”…解决方法

前端开发:报错Error in created hook:”SyntaxError:Unexpected token u in JSON at position 0”…解决方法

作者:互联网

前言

前段时间在做前端开发的过程中遇到一个关于JSON.parse()的使用的报错问题,JSON.parse()通常是用来对JSON对象和字符串之间的相互转换的,所以一般在使用的时候遇到相关报错就是因为在使用的时候没有做相应的非空判断,或者是数据格式错误造成的。那么本文就来分享一下关于使用JSON.parse()进行字符串和JSON对象相互转换的时候遇到的报错问题。

报错提示

具体的报错信息如下所示:

vue.esm.js?efeb:628 [Vue warn]: Error in created hook: "SyntaxError: Unexpected token u in JSON at position 0"

found in

---> <PositionDetail> at src/views/TalentScout/PositionDetail.vue

       <Layout> at src/views/Layout.vue

         <App> at src/App.vue

           <Root>

SyntaxError: Unexpected token u in JSON at position 0

    at JSON.parse (<anonymous>)

    at VueComponent.created (PositionDetail.vue?b477:114)

    at invokeWithErrorHandling (vue.esm.js?efeb:1872)

    at callHook (vue.esm.js?efeb:4244)

    at VueComponent.Vue._init (vue.esm.js?efeb:5031)

    at new VueComponent (vue.esm.js?efeb:5177)

    at createComponentInstanceForVnode (vue.esm.js?efeb:3313)

    at init (vue.esm.js?efeb:3142)

    at merged (vue.esm.js?efeb:3331)

    at createComponent (vue.esm.js?efeb:6033)

 

分析

        通过对上述报错的提示信息分析之后,得出该报错是由于JSON.parse()在使用过程中没有对数据源进行判断处理。例如需要处理转换的数据源为空值不存的时候在或者格式改变的时候,这时候不对数据源做对应的处理,直接使用JSON.parse(),必然报错。

        上述报错的错误就是由于使用JSON.parse()的时候没有判断数据,数据源为空造成的报错。一般在接口取数据转换为JSON数据时,经常会遇到这个错误,很有可能是数据未获得到,或者是取到的数据源不是JSON字符串,那么本文以只考虑第一种数据未取到或者为空的这种情况来讲。

解决方法

这里以只考虑数据未取到或者为空的这种情况来讲解解决方法。

在解决上述报错问题之前,首先来看一下未对数据源处理的时候的JSON.parse()的使用代码,如下所示:

 this.jdList = JSON.parse(this.detail.otherInfo); //这段代码直接使用JSON.parse来进行转换,这样做是很危险的,万一数据源为空,绝对要挂,必报错

那么接下来就来分享一下正确的处理方法,方法也很简单,直接对需要转化类型的数据源进行非空判断处理即可,对上面的示例进行修改,如下所示:

  this.jdList =  this.detail.otherInfo&& JSON.parse(this.detail.otherInfo);  //如果数据源为空的时候不执行,这样即可完美解决数据源为空的时候使用JSON.parse造成的报错问题。

 

以上就是本章全部内容,欢迎关注三掌柜的微信公众号“程序猿by三掌柜”,三掌柜的新浪微博“三掌柜666”,欢迎关注!

三掌柜的微信公众号:

 

三掌柜的新浪微博:

 

标签:vue,created,数据源,parse,JSON,Unexpected,报错,esm
来源: https://blog.csdn.net/CC1991_/article/details/118967139