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

小程序使用json.parse出现的问题;
在这里插入图片描述
原因
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()将变量还原,这样子就能达到预期效果了。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值