小程序json字符串转 json对象 "{ name :"你好"}" 转成 { name :"你好"}

解决后端接口返回 var obj ="{ name :"你好"}" 类似这样的数据,对象或者数组外面包了一层引号,

把这种数据转成 var obj = { name :"你好"};

直接上代码:

// pages/test/test.js
Page({
  jsonStrToJson(jsonStr) {
    try {
      jsonStr = jsonStr.replace(" ", "");
      if (typeof jsonStr != 'object') {
        jsonStr = jsonStr.replace(/\ufeff/g, "");
        return JSON.parse(jsonStr);
      }
    } catch (err) { 
      console.log(err)
    }
  },
  
  onLoad: function (options) {
    wx.request({
      url: 'test.php', //仅为示例,并非真实的接口地址
      data: {
        x: ''
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data)
        res.data = this.jsonStrToJson(res.data);
        console.log('res.data', res.data);
      }
    })
  },

})
发布了387 篇原创文章 · 获赞 774 · 访问量 183万+

猜你喜欢

转载自blog.csdn.net/qq_35713752/article/details/103713284