0

I'm new to google scripts and I want to fetch data from an URL when the user is logged in. I wrote some code but when I execute it the following error appears: SyntaxError: Unexpected token: T

I know that this question has been asked before, but I can't find a solution for my issue...

function myFunction() {
  var endpoint = 'rule-sets';
  var url = 'https://example.com/api/'+endpoint;
  var restHeaders = {    
    'X-Application-Key': 'f3ez1a48f06838b7238z20cff80e010bf0c42cfp',
    'Authorization':'Bearer bm9scnVuMDQ4Z2FvaWpvdHBqa2Y1djA5WWavTiElV5DyYjdxb3UxNnVyMzRoNWhsISPBmXNyZDFtMCYzMDk2JjE0NjE5MDI3NTYwODI=',
  }
  var options = {
    'method' : 'get',
    'headers': restHeaders, 
    'muteHttpExceptions': true,
  };
  var urlResponse = JSON.parse(UrlFetchApp.fetch(url, options));
  Logger.log(urlResponse);
  Logger.log(urlResponse.data.length);
}

1 Answer 1

2

Looking at https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#methods signature it looks like it will be this:

var urlResponse = UrlFetchApp.fetch(url, options);
var jsonContent = JSON.parse(urlResponse.getContentText());
Logger.log(jsonContent);
Logger.log(jsonContent.data.length);

You were parsing the return value of fetch which is an object.

Sign up to request clarification or add additional context in comments.

6 Comments

Ok, but now I get Syntax error on this line .then((response) => response.json())
My browser supports es6 arrow functions...Another error appears after I tried to implement the second code TypeError: Cannot find function then in object The supplied authentication is invalid.
What is UrlFetchApp? I was assuming it was something like github.com/github/fetch. What does it return?
developers.google.com/apps-script/reference/url-fetch/… A script can use the URL Fetch service to issue HTTP and HTTPS requests and receive responses. It returns an Object
Do you have an idea how can I loop through jsonData (array) and display each elements on separate lines? I tried the following but it returns 1:[object Object] ... 16:[object Object] instead of json data: for (i=0; i<jsonContent.length; i++) { Logger.log(i + ":" + jsonContent[i]); }
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.