在Javascript中解析和提取JSON

时间:2022-08-26 11:58:47

I'm using Google geocoding API and trying to get the value: 9.081999, and 8.675276999999999 respectively in the the following Google geocoding JSON data in Javascript.

我正在使用Google地理编码API并尝试在Javascript中的以下Google地理编码JSON数据中分别获取值:9.081999和8.675276999999999。

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Nigeria",
               "short_name" : "NG",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Nigeria",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 13.8856449,
                  "lng" : 14.677982
               },
               "southwest" : {
                  "lat" : 4.2464428,
                  "lng" : 2.676932
               }
            },
            "location" : {
               "lat" : 9.081999,
               "lng" : 8.675276999999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 13.8856449,
                  "lng" : 14.677982
               },
               "southwest" : {
                  "lat" : 4.2464428,
                  "lng" : 2.676932
               }
            }
         },
         "partial_match" : true,
         "place_id" : "ChIJDY2kfa8LThARyAvFaEH-qJk",
         "types" : [ "country", "political" ]
      }
   ],
   "status" : "OK"
}

But when I do this:

但是当我这样做时:

var myJSONResult = $.parseJSON(request.responseText);
var myAddress = Array();
for (i = 0; i < myJSONResult.results.length; i++) {
        myAddress[i] = myJSONResult.results[i].geometry.location;
}

It returns Undefined

它返回Undefined

Any help is appreciated, Thanks.

任何帮助表示赞赏,谢谢。

1 个解决方案

#1


0  

try this

var myJSONResult = request.responseText;
var myAddress = Array();
for (i = 0; i < myJSONResult.results.length; i++) {
        myAddress[i] = myJSONResult.results[i].geometry.location;
}

No need of using $.parseJSON(), since your response is already a JSON object.

不需要使用$ .parseJSON(),因为您的响应已经是JSON对象。

#1


0  

try this

var myJSONResult = request.responseText;
var myAddress = Array();
for (i = 0; i < myJSONResult.results.length; i++) {
        myAddress[i] = myJSONResult.results[i].geometry.location;
}

No need of using $.parseJSON(), since your response is already a JSON object.

不需要使用$ .parseJSON(),因为您的响应已经是JSON对象。