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. Commented Nov 30, 2015 at 19:11
  • @Teemu, in GAS, it is synchronous. Commented 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));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Riël. your solution worked. Here's what I ended up doing.
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);
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.