繁体   English   中英

无法解析来自服务器的JSON格式的响应

[英]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包含字符串值而不是latlng属性的数字值,则需要解析它们:

{
 "location": {
  "lat": "12.9621211",
  "lng": "77.64804099999999"
 },
 "accuracy": 740.0
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM