小程序里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 }) } }) }, }) },