[英]Can't parse JSON formatted response from server
我正在嘗試解析JSON格式的字符串,例如
var json_response = JSON.parse(response);
響應如下。 這是來自Google API的格式化JSON響應。
{
"location": {
"lat": 12.9621211,
"lng": 77.64804099999999
},
"accuracy": 740.0
}
但是我收到一個錯誤消息
Uncaught SyntaxError: Unexpected token {
我在SO中檢查了很多答案。 他們中的很多人都說上述json響應已經是一個對象。 但是當我嘗試
console.log(response["location"]);
console.log(response.location);
我得到以下輸出
undefined
undefined
我究竟做錯了什么 ?
編輯:
console.log(response);
給
{
"location": {
"lat": 12.9621211,
"lng": 77.64804099999999
},
"accuracy": 740.0
}
更新:
當我嘗試以下
console.log('"'+response+'"');
我懂了
"{
"location": {
"lat": 12.962118199999999,
"lng": 77.6480399
},
"accuracy": 739.0
}
"
似乎在結束}之后有多余的一行。 那會有所作為嗎?
我將整個功能粘貼到這里。 對不起,如果我之前不清楚。
function get_distance_from_cellTower(json){
$.ajax({type: 'POST', url:"get_location.php",data:getformurlencoded(json),
success:function(response){
console.log('"'+response+'"');
var latitude;
var longitude;
var success;
var json_response;
try{
json_response = JSON.parse(response);
if(json_response.hasOwnProperty("error")){
success = 0;
console.log(json_response.error);
append_to_show(json_response.error);
}
if(json_response.hasOwnProperty("location")){
success = 1;
}
}
catch(e){
console.log(e);
append_to_show(e);
}
if(success){
var location = JSON.parse(json_response.location);
latitude = parseFloat(location.lat);
longitude = parseFloat(location.lng);
var distance = calculate_distance_kms(latitude, doclat, longitude, doclong);
append_to_show("cell tower: "+distance);
console.log("Cell tower: "+distance);
}
},
error:function(err){
console.log(err);
append_to_show(err);
},contentType:'application/x-www-form-urlencoded'});
}
問題是您還試圖解析下一個級別。 從JSON解析為對象時,它將解析所有級別。 您將獲得一個包含對象的對象,而不是包含需要解析的JSON字符串的對象。
只需從屬性獲取對象:
var location = json_response.location;
解析JSON時,值將轉換為適當的數據類型,因此您無需解析它們:
latitude = location.lat;
longitude = location.lng;
如果JSON包含字符串值而不是lat
和lng
屬性的數字值,則需要解析它們:
{
"location": {
"lat": "12.9621211",
"lng": "77.64804099999999"
},
"accuracy": 740.0
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.