首页 文章

使用jQuery访问嵌套的json值

提问于
浏览
-1

我想从此Google Maps API调用中获取几何/位置lat和lng值http://maps.google.com/maps/api/geocode/json?address=Marshal+Tito+12+Skopje&sensor=false

我尝试了一些方法,但它没有得到我需要的数据,这是我尝试的:

var result = JSON.parse(data);
console.log(result[0].results.geometry);
console.log(result.results[0].geometry);

但是我得到了未定义的值 .

为了获得几何/位置(lat,lng)值,我需要修改什么?

2 回答

  • 2

    您需要按名称访问嵌套对象,如: results[0].geometry.location.lat

    在这里http://jsfiddle.net/5pjha/

  • 0

    要访问对象,您可以使用点( . )来访问嵌套对象,例如,

    const user = {
      firstName: 'Alongkorn',
      lastName: 'Chetasumon',
      age: 25,
      address: {
        country: 'Thailand',
        location: {
          lat: 123,
          lng: 456
        }
      }
    };
    
    const lat = user.address.location.lat;
    console.log(lat); // print 123
    

    来自http://maps.google.com/maps/api/geocode/json?address=Marshal+Tito+12+Skopje&sensor=false

    通过 results[0].geometry.location.latresults[0].geometry.location.lng 获取 latlng

相关问题