简体   繁体   中英

Can't call a part of an object after parsed as JSON in Google Apps Script

I'm trying to make some code that can pull from an API and pull out a piece from the response. My code is below.

var response = UrlFetchApp.fetch('https://[API_URL]', options);
   Logger.log(response.getContentText());
  var firstCall = response.getContentText();
  var JsonObj = JSON.parse(firstCall);
  Logger.log(firstCall['id']);
  sheet.appendRow(['successfully connected to API.']);
  sheet.appendRow([Logger.getLog()]);

A sample response from the API is below.

[{"id":12345678901234567,"name":"email@email.com - someText"}]

When I try to run the first code, it completes the code, logging the above line and undefined. My goal is to get just the ID from the string. Thanks for your help!

You're almost there. To keep it simple, do it like this:

function getURLFromSite(){

     var response = UrlFetchApp.fetch('https://jsonplaceholder.typicode.com/users');
     var JsonObj = JSON.parse(response);
       Logger.log(JsonObj[1].name);

}

Here's JsonObj is like an array which you can access using JsonObj[0] , JsonObj[1] and JsonObj[2] .

To access properties like id or name , just use the dot notation like JsonObj[0].id or JsonObj[1].name .

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