小程序使用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()将变量还原,这样子就能达到预期效果了。
本文探讨了在小程序中使用JSON.parse解析特定URL时遇到的问题,由于JSON.parse无法识别URL中的特殊字符导致错误。通过使用encodeURIComponent和decodeURIComponent函数,有效地解决了JSON数据与URI组件之间的编码冲突,确保了数据的正确传递。
7121

被折叠的 条评论
为什么被折叠?



