Pavel Valeriu Pavel Valeriu - 5 months ago 35
Javascript Question

How to extract data from url fetch response

I implemented a fetch method using Google Script and it returns me the following log:

[16-06-10 14:06:03:942 EEST] {
"accessToken": "data",
"userId": 3096,
"created": "2016-06-10T05:06:03.799-06:00"
}


Does anyone know how can I extract the value from
accessToken
?

Here is my gs code:

var url = "https://example.com"
var payload = {
'username' : "user",
'password' : "pass",
}
var options = {
'method' : 'post',
'payload': JSON.stringify(payload),
};
var urlResponse = UrlFetchApp.fetch(url, options);
Logger.log(urlResponse); //this returns me the log shown above


Basically I want to add the "data" value from
accessToken
to a variable
getData
.

Answer

I think that even if the variable urlResponse look to be an object it will only return you some string value. You should try to do something like that:

var data = JSON.parse(urlResponse.getContentText());
Logger.log(data.accessToken);
Comments