简体   繁体   中英

How to access object in parsed nested JSON in Google Apps Script

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

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.com/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!

When working with complicated 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, ie data.routes[0].legs[0].steps[0].polyline (which returns the polyline object).

I've a similar issue.

[
{
    "NOMBRE": "ViejosNoUsarEl Quebrachal",
    "ACTIVO": false,
    "CODIGO": "ViejosNoUsarQUEB",
    "CALLE": null,
    "NUMERO": null,
    "PROVINCIA": "Jujuy",
    "LOCALIDAD": "EL MORRO",
    "ZONA": null,
    "SUPERFICIE": 3900,
    "CODIGOEXTERNO": ""
},
{
    "NOMBRE": "ViejoNoUsarSanta Teresa",
    "ACTIVO": false,
    "CODIGO": "ViejoNoUsarST",
    "CALLE": null,
    "NUMERO": null,
    "PROVINCIA": "San Luis",
    "LOCALIDAD": "Villa MercedesOLD",
    "ZONA": "Oeste",
    "SUPERFICIE": 3700,
    "CODIGOEXTERNO": ""
},
{
    "NOMBRE": "ViejosNoUsarGil",
    "ACTIVO": false,
    "CODIGO": "ViejosNoUsarGIL",
    "CALLE": null,
    "NUMERO": null,
    "PROVINCIA": "Cordoba",
    "LOCALIDAD": "9 DE JULIO",
    "ZONA": "Oeste",
    "SUPERFICIE": 200,
    "CODIGOEXTERNO": ""
},
{
    "NOMBRE": "ViejosNoUsarDon Manuel",
    "ACTIVO": false,
    "CODIGO": "ViejosNoUsarDM",
    "CALLE": null,
    "NUMERO": null,
    "PROVINCIA": "Cordoba",
    "LOCALIDAD": "9 DE JULIO",
    "ZONA": "Oeste",
    "SUPERFICIE": 400,
    "CODIGOEXTERNO": ""
}
]

That is my JSON, I want to create as much rows as objects in the array on a google sheet using google apps script.

In this case there would be 4 google sheet rows. I want to parse only the values of the properties.

As an example, the first row would look like this:

ViejosNoUsarEl Quebrachal | false | ViejosNoUsarQUEB | null | null | Jujuy | EL MORRO | null | 3900 |

This is the code I'm using in apps script:

function doGet() {

let config = {
muteHttpExceptions: true,
method: "get"
};

let response = UrlFetchApp.fetch("https://j11.teamplace.finneg.com/BSA/api/reports/ApiEstablecimiento?ACCESS_TOKEN=2c96e31c-5a27-4694-953b-cd08fcaf3997", config);

var spreadsheetId = "1opWEqkg29aCpZKOY-zDlO-RfprwrNq6FMiHMTWkYtXQ";
var sheetName = "Hoja 3";
var sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName(sheetName);
var rows = response.rows;

var data = JSON.parse(response.getContentText());

Logger.log(data.provincia);

for(var i = 0; i < data.rows.length; i++){
sheet.appendRow(data.rows[i])
}
return ContentService.createTextOutput(JSON.stringify({sheet:sheetName, rows: 
rows}))
}

The problem is that I cant get the dot notation to extract the values I want. For example, Logger.log(data.provincia); prints "Information null".

@haf-decent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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