小程序页面传参报错:Syntax Error: Unexpected end of JSON input 问题解决

1,669 阅读1分钟
//item:
{"id":16,"storeId":"611","actId":"000000000005","businessAccount":"0062299","erpCode":"20002718","mallGoodNo":null,"actMoney":0.01,"stock":20,"numLimit":null,"sort":1,"topFlag":"0","beginTime":"09:00:00","endTime":"10:00:00","storeNa":"XXXX店","goodNa":"花蜜轻质精油50ml","mallGoodNa":null,"businessAccountNa":"迪奥","goodPrice":null,"priceSection":"1~2450","vipId":null,"saleQty":null,"imgSrc":"https://www.XXX365.com/fileserver/file/download?id=f81defdd76814d11bfa697dccb27be51"}

//页面A
wx.navigateTo({
   url: "/pages/goods-details/index?item=" + JSON.stringify(item) + "&isseckill=1"
})

//页面B
onLoad: function (options) { 
    let item = options.item;
    item = JSON.parse(item);
    console.log('item',item)
}

报错: Syntax Error: Unexpected end of JSON input 

原因: Syntax Error: Unexpected end of JSON input 直译过来是:语法错误:JSON输入的意外结束,即不符合 JSON 的转化规则,那么,什么情况会产生这个报错呢?

目前我知道的有两种: 

1." " 双引号 与 ' ' 单引号混用,(我这里没有,再找); 

2. url转码不规范,(额...好吧,这里中枪了)

看来是 imgSrc 这个属性的属性值 产生的这个报错:

let imgSrc="https://www.XXX365.com/fileserver/file/download?id=f81defdd76814d11bfa697dccb27be51"
encodeURIComponent(imgSrc)
/*
*   "https%3A%2F%2Fwww.XXX365.com%2Ffileserver%2Ffile%2Fdownload%3Fid%3Df81defdd76814d11bfa697dccb27be51"
*/
decodeURIComponent( "https%3A%2F%2Fwww.XXX365.com%2Ffileserver%2Ffile%2Fdownload%3Fid%3Df81defdd76814d11bfa697dccb27be51" )
/*
*    "https://www.XXX365.com/fileserver/file/download?id=f81defdd76814d11bfa697dccb27be51"
*/

找到了原因,那个修改下:

//页面A
item = encodeURIComponent(JSON.stringify(item));
wx.navigateTo({
   url: "/pages/goods-details/index?item=" + item + "&isseckill=1"
})

//页面B
onLoad: function (options) { 
    let item = options.item;
    item = JSON.parse(decodeURIComponent(item));
    console.log('item',item)
}

ok,问题解决了