解决 SyntaxError:Unexpected end of JSON input 或 Unexpected token u in JSON at position 0 问题

1、报错原因

JSON 接收的数据不完整,或者数据格式不符合要求,如 undefined

2、JSON 数据格式要求 

1、JSON文件都是被包裹在一个大括号中 {},通过key-value的方式来表达数据。
2、JSON的Key必须包裹在一个双引号中,在实践中,编写 JSON 的时候,忘了给 Key 值加双引号或者是把双引号写成单引号是常见错误。
3、JSON的值只能是以下几种数据格式,其他任何格式都会触发报错,例如 JavaScript 中的 undefined。
    1)数字,包含浮点数和整数
    2)字符串,需要包裹在双引号中
    3)布尔值,true 或者 false
    4)数组,需要包裹在方括号中 []
    5)对象,需要包裹在大括号中 {}
    6)null
    7)其它类型,如日期,(JSON)本身不支持,应该由解析器/客户端处理转换为字符串
4、对象或数组每个成员后面必须跟一个逗号,如果它不是最后一个的话
5、JSON.parse() 不允许用逗号作为结尾

3、解决方法

对象/数组先要通过JSON.stringify转化为字符串再通过encodeURIComponent编码,接收时,先通过decodeURIComponent解码再通过JSON.parse转换为JSON格式的对象/数组
// 跳转页面传输数据
  toChildrenDetails(e) {
    let data = e.currentTarget.dataset.info
    if (data) {
      var info = {
        name: data.name,
        sex: data.sex,
        href: data.face_image,
        number: data.number,
        age: data.age
      }
      wx.navigateTo({
        url: './children-details/children-details?data=' + encodeURIComponent(JSON.stringify(info))
      })
    } else {
      wx.showToast({
        title: '数据为空!',
        icon: 'none'
      })
    }
  },
// 接收数据
onLoad: function (options) {
  this.setData({
    info: JSON.parse(decodeURIComponent(options.data))
  })
},

猜你喜欢

转载自blog.csdn.net/weixin_46258341/article/details/131804093