gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 13:24:48 25 4
gpt4 key购买 nike

我正在尝试解析 JSON 格式的字符串,例如

var json_response = JSON.parse(response); 

回复如下。这是来自 Google api 的格式化 JSON 响应。

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

但是我收到一条错误消息

Uncaught SyntaxError: Unexpected token {

我查了很多答案。很多人说上面的 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
}

关于javascript - 无法解析来自服务器的 JSON 格式的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30014565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com