小程序报错:Unexpected end of JSON input的问题分析,是使用了json.parse时存在特殊字符

小程序使用json.parse出现的问题;
小程序报错:Unexpected end of JSON input的问题分析,是使用了json.parse时存在特殊字符_第1张图片
原因
JSON.parse无法识别某些url中的特殊字符,所以报错

payment.js中

gotoDetailPage: function (e) {
var that = this;
const expense_id = e.currentTarget.dataset.expenseId

var list = that.data.expense
let thisPur = list.filter(item => item.id == expense_id)[0];
var nextDatas = JSON.stringify(thisPur)
console.log("nextDatas>>>>>>>>", nextDatas)
wx.navigateTo({
  url: '/pages/paymentDetail/paymentDetail?details=' + encodeURIComponent(nextDatas)
});

},

跳转页:paymentDetail.js

onLoad: function (options) {
var that = this
console.log(“options>>>”, options)
var newData= decodeURIComponent((options.details));
var payDetailList = JSON.parse(newData);
}

解决方案

我们在JSON.stringify()之后将变量使用encodeURIComponent函数处理,这个encodeURIComponent() 函数可以把字符串作为 URI 组件来进行编码。在跳转到目标页面接收时用decodeURIComponent对URI 组件进行解码,后面在通过JSON.parse()将变量还原,这样子就能达到预期效果了。

你可能感兴趣的:(小程序,json.parse,Unexpected,end,of,JSON,input,小程序)