小程序json字符串转为对象

小程序里json字符串转为对象使用JSON.parse()方法转变无效, 看报错提示有单引号“ ' ” 因为单引号而无效, 将单引号全改双引号即可.

报错如下:

VM11050:1 thirdScriptError
Unexpected token ' in JSON at position 1;at pages/address/address onLoad function;at api getStorage success callback function
SyntaxError: Unexpected token ' in JSON at position 1...

 截图如下:

错误注释,已改正如下:

    wx.getLocation({
            success: function (res) {
                var lng = res.longitude;
                var lat = res.latitude;
                var requestUrl = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lng + "&key=D6CBZ-D7PHQ-G7L54-GZJKF-B3PDK-MZBR4"
                wx.request({
                    url: requestUrl,
                    success: function (res) {
                        var province = res.data.result.address_component.province;
                        var city = res.data.result.address_component.city;
                        var district = res.data.result.address_component.district;
                        var address = res.data.result.address;
                //不识别单引号,下面一行改正// var location = "{'province': '" + province + "','city':'" + city + "','district':'" + district + "','address':'" + address + "','lng':" + lng + ",'lat':" + lat + "}"
var location = "{"province": "" + province + "","city":"" + city + "","district":"" + district + "","address":"" + address + "","lng":"" + lng + "","lat":"" + lat + ""}";
                     
                        wx.setStorage({
                            key: 'location_key',
                            data: location
                        })
                    }
                })
            },
        })
    },
原文地址:https://www.cnblogs.com/wangduojing/p/9896267.html