最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to access object in parsed nested JSON in Google Apps Script - Stack Overflow

programmeradmin4浏览0评论

Broad spectrum apology, to start off with, for any mistakes relating to being a n00b when it es to code, js, Google Apps Script and indeed stackoverflow.

I am trying to extract the polyline from an API call to Google Maps' Directions API. Parsed from the API results, I get:

{routes=[{summary=A215, copyrights=Map data ©2017 Google, legs=[{duration={text=18 mins, value=1108}, start_location={lng=-0.1295712, lat=51.4227696}, distance={text=7.2 km, value=7187}, start_address=London SW16 6ET, UK, end_location={lng=-0.0706306, lat=51.3869032}, duration_in_traffic={text=15 mins, value=882}, end_address=Woodside Green, London SE25 5EU, UK, via_waypoint=[], steps=[{duration={text=1 min, value=6}, start_location={lng=-0.1295712, lat=51.4227696}, distance={text=29 m, value=29}, travel_mode=DRIVING, html_instructions=Head <b>north</b> on <b>Streatham High Rd</b>/<b>A23</b> toward <b>Streatham Common N</b>/<b>A214</b>, end_location={lng=-0.1297011, lat=51.42301399999999}, polyline={points=iozxHxhXo@X}},....

My script is as follows:

function listJourneyPoints(value) {

  //Temporary url for var value
  var value = ";destination=SE25%205EU&mode=driving&region=UK&departure_time=1507676400&key=AIzaSyDbswrt7RFy3s13ulO9BUY9jQUNchUfi4o";

  //Call the google route planner api
  var routeResponse = UrlFetchApp.fetch(value);

  //Parse JSON from routeResponse
  var json = routeResponse.getContentText();
  var data = JSON.parse(json);

  //Get the polyline
  var polyl = data["routes"]["legs"]["steps"]["polyline"];
  Logger.log (polyl);

}

I can't work out how to navigate through the arrays and objects to the polyline. I know that dot notation doesn't work with arrays so have used square brackets, but whatever I try I cannot progress past data["routes"]["legs"] without getting 'TypeError: cannot read property "steps" from undefined'. I'm aware the problem probably lies with my not understanding the data structure, but after hours of searching, including using an online Json Parser to elucidate the structure, I'm still stuck, so would be grateful for any help. Thanks!

Broad spectrum apology, to start off with, for any mistakes relating to being a n00b when it es to code, js, Google Apps Script and indeed stackoverflow..

I am trying to extract the polyline from an API call to Google Maps' Directions API. Parsed from the API results, I get:

{routes=[{summary=A215, copyrights=Map data ©2017 Google, legs=[{duration={text=18 mins, value=1108}, start_location={lng=-0.1295712, lat=51.4227696}, distance={text=7.2 km, value=7187}, start_address=London SW16 6ET, UK, end_location={lng=-0.0706306, lat=51.3869032}, duration_in_traffic={text=15 mins, value=882}, end_address=Woodside Green, London SE25 5EU, UK, via_waypoint=[], steps=[{duration={text=1 min, value=6}, start_location={lng=-0.1295712, lat=51.4227696}, distance={text=29 m, value=29}, travel_mode=DRIVING, html_instructions=Head <b>north</b> on <b>Streatham High Rd</b>/<b>A23</b> toward <b>Streatham Common N</b>/<b>A214</b>, end_location={lng=-0.1297011, lat=51.42301399999999}, polyline={points=iozxHxhXo@X}},....

My script is as follows:

function listJourneyPoints(value) {

  //Temporary url for var value
  var value = "https://maps.googleapis./maps/api/directions/json?origin=SW16%206ET&destination=SE25%205EU&mode=driving&region=UK&departure_time=1507676400&key=AIzaSyDbswrt7RFy3s13ulO9BUY9jQUNchUfi4o";

  //Call the google route planner api
  var routeResponse = UrlFetchApp.fetch(value);

  //Parse JSON from routeResponse
  var json = routeResponse.getContentText();
  var data = JSON.parse(json);

  //Get the polyline
  var polyl = data["routes"]["legs"]["steps"]["polyline"];
  Logger.log (polyl);

}

I can't work out how to navigate through the arrays and objects to the polyline. I know that dot notation doesn't work with arrays so have used square brackets, but whatever I try I cannot progress past data["routes"]["legs"] without getting 'TypeError: cannot read property "steps" from undefined'. I'm aware the problem probably lies with my not understanding the data structure, but after hours of searching, including using an online Json Parser to elucidate the structure, I'm still stuck, so would be grateful for any help. Thanks!

Share Improve this question asked Oct 10, 2017 at 15:32 Nathan NorthNathan North 211 silver badge5 bronze badges 1
  • 1 First off, "routes" is not an object but an array of objects so it has to be indexed using numbers; same goes for "legs" and "steps". So to get the polyline property of the first object in the steps array, of the first of object of the legs array, of the first object of the routes array, you'd write the following: data.routes[0].legs[0].steps[0].polyline – TheAddonDepot Commented Oct 10, 2017 at 16:22
Add a ment  | 

1 Answer 1

Reset to default 6

When working with plicated nested JSON, I like to Logger.log() multiple times as I navigate through it to get a better look at what's going on. Even without that though, adding some formatting to the JSON to see the structure of it and removing unneeded entries can both be helpful in seeing how to access specific elements:

{
  routes: [{
    legs: [{
      steps: [{
        polyline: {
          points: iozxHxhXo@X
        }
      }]
    }]
  }]
}

So the first thing to notice is that routes holds an array, which means we need to access its indices to access the nested objects. Luckily, all of the nested elements are wrapped in an object so we can just access the first element of the array: data["routes"][0]. If I continue to have trouble as I work my way down into the nested objects, I'll keep using Logger.log(data["routes"][0]...) to see what the next key/index should be.

It looks like you had a pretty good idea of the hierarchy and you were just missing the array portion of the objects, which is why you were getting the errors. So adding in [0]'s after each key call should fix your problem.

Also, just as a sidenote, you can use dot notation when accessing keys in an object in Google Scripts, i.e. data.routes[0].legs[0].steps[0].polyline (which returns the polyline object).

发布评论

评论列表(0)

  1. 暂无评论