1

I'm trying to parse JSON I recieved from an API call, but I keep running into the error "TypeError: Cannot read property "id" from undefined. (line 42, file "")" I'm relatively new to Apps Script. Any ideas on what's going on? I can get the payload back in JSON, but can't seem to parse it.

function getInfo() {
    var url = "https://subdomain.chargify.com/subscriptions.json";
    var username = "xxx"
    var password = "x"

    var headers = {
        "Authorization": "Basic " + Utilities.base64Encode(username + ':' + password)
    };

    var options = {
        "method": "GET",
        "contentType": "application/json",
        "headers": headers
    };

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

    var id = data.subscription; // kicks back an error
    // var id = data;    works and returns the whole JSON payload

    var ss = SpreadsheetApp.getActiveSheet()
    var targetCell = ss.setActiveSelection("A1");
    targetCell.setValue(id);
}
2
  • 3
    what does your logging of data show? obviously there's no subscription key at the top-level of the structure.
    – Marc B
    Nov 30, 2015 at 19:11
  • @Teemu, in GAS, it is synchronous.
    – Riël
    Nov 30, 2015 at 20:45

2 Answers 2

1

According to the documentation here https://docs.chargify.com/api-subscriptions#api-usage-json-subscriptions-list

it returns an array of subscriptions when you call the /subscriptions.json endpoint. So probably your data object should be handled like:

for (var i=0;i<data.length;i++) {
var item = data[i]; //subscription object, where item.subscription probably works
Logger.log(JSON.stringify(item));
}
1
  • Thanks Riël. your solution worked. Here's what I ended up doing. Dec 1, 2015 at 0:41
0
function getInfo() {
    var url = "https://subdomain.chargify.com/subscriptions.json";

    var username = "xxx"
    var password = "x"

    var headers = {
        "Authorization": "Basic " + Utilities.base64Encode(username + ':' + password)
    };

    var options = {
        "method": "GET",
        "contentType": "application/json",
        "headers": headers
    };

    var response = UrlFetchApp.fetch(url, options);
    var data = JSON.parse(response.getContentText());

    for (var i = 0; i < data.length; i++) {
        var item = data[i]; //subscription object, where item.subscription probably works
        Logger.log(JSON.stringify(item));
        var subscriptionid = item.subscription.id;
    }

    var ss = SpreadsheetApp.getActiveSheet()
    var targetCell = ss.setActiveSelection("A2");
    targetCell.setValue(subscriptionid);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.