Encountering an Unknown Error while Parsing JSON in Google Apps Script

Having trouble parsing JSON data retrieved from an API call. The error message "TypeError: Cannot read property "id" from undefined. (line 42, file "")" keeps popping up. I'm fairly new to Apps Script. Any thoughts on what might be causing this issue? I am able to fetch the payload in JSON format, but struggling to parse it.

function fetchInfo() {
    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; // triggers an error
    // var id = data;    works and returns the entire JSON data

    var ss = SpreadsheetApp.getActiveSheet()
    var targetCell = ss.setActiveSelection("A1");
    targetCell.setValue(id);
}

Answer №1

The guide located at

states that the /subscriptions.json endpoint will provide an array of subscriptions. Therefore, it is recommended to handle your data object like this:

for (let i=0; i<data.length; i++) {
let item = data[i]; //subscription object, accessing item.subscription will likely work
Logger.log(JSON.stringify(item));
}

Answer №2

function fetchSubscriptionID() {
    var endpoint = "https://example.com/subscriptions.json";

    var user = "abc"
    var pass = "123"

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

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

    var responseData = UrlFetchApp.fetch(endpoint, request);
    var subscriptionData = JSON.parse(responseData.getContentText());

    for (var j = 0; j < subscriptionData.length; j++) {
        var subItem = subscriptionData[j]; //subscription object, where subItem.subscription probably works
        Logger.log(JSON.stringify(subItem));
        var subID = subItem.subscription.id;
    }

    var sheet = SpreadsheetApp.getActiveSheet()
    var cell = sheet.setActiveSelection("A2");
    cell.setValue(subID);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fiasco in Parsing JSON Using Objective-C

I have been trying to troubleshoot the following code snippet, but I keep running into a nil response. Despite attempting multiple variations, I find myself in a cycle of failure. Here is the data retrieved from the server - [{"description":"yolo.","na ...

Python: Exploring JSON Data

Is there a way to extract data specific to a district (such as Nicobars, North and Middle Andaman...) from ? I am trying to extract the Active cases by simply searching for the district name without having to specify the state every time. Currently, I&apos ...

Evaluation of Library (VueJS) - Displaying various components in an individual test case

Just starting out with testing and have a simple question: I am working on testing a checkbox component. I understand the basics, but how can I render multiple components within one it block? Here is my current code. I am stuck on the second test where I ...

Maintaining Flexbox layout without triggering item re-rendering for a new container

This is the unique layout I'm aiming to create: I am facing a challenging flexbox layout that needs to be implemented. One of the items in this layout is a Webgl player, which cannot be conditionally rendered due to the restarting issue it may cause. ...

ridiculing callback within parameter

I have a model setup in the following way: export class MyClass { grpcClient: MyGRPCClient; constructor(config: MyGRPCClientConfig) { this.grpcClient = new MyGRPCClient( config.serverUrl, grpc.credentials.createInsecure(), ); ...

Personalize Your Highcharts Legend with Custom HTML

Currently, I am working on a project with a highcharts graph where I need to gather data from the user regarding each line displayed. My goal is to include a text input box next to each label in the legend that relates to the series name. Once the user ent ...

How can I properly consume the variables 'b0' and 'b1' from the JSON response in my Java POJO class?

How can I access the 'b' variable data from a JSON response containing 'b0' and 'b1' variables in my Java POJO? Here is an example of the JSON response: { "@a":"abc", "b0":{ "@name":"b0", "@nodes":[]}, "b1":{ ...

Utilize React Redux to send state as properties to a component

When my React Redux application's main page is loaded, I aim to retrieve data from an API and present it to the user. The data is fetched through an action which updates the state. However, I am unable to see the state as a prop of the component. It s ...

There was a problem establishing a WebSocket connection to 'ws://127.0.0.1:2000/'. The attempt failed with the following error: net::ERR_CONNECTION_REFUSED

I have integrated websocket functionality using a repository found at https://github.com/kishor10d/CodeIgniter-Ratchet-Websocket After successfully testing the websocket on my local environment, I encountered issues when uploading the files to the live se ...

A step-by-step guide on uploading a CSV file in Angular 13 and troubleshooting the error with the application name "my

I am currently learning angular. I've generated a csv file for uploading using the code above, but when I try to display it, the screen remains blank with no content shown. The page is empty and nothing is displaying Could it be that it's not ...

Utilize the Google reverse geocoding API to convert latitude and longitude values from JSON into a dynamic variable

I have been utilizing the NPM Geocoder to convert locations into latitude and longitude coordinates, but I am struggling with extracting the lat and long values from the output. Below is the JSON data, and my goal is to store the values on lines 59 and 60 ...

Automatically toggle Bootstrap checkbox switch to OFF upon successful completion of AJAX script

On my Employee screen, I have an HTML Form with a Bootstrap Checkbox Switch that toggles the visibility of password change fields. Clicking it reveals or hides the fields accordingly. I'd like to set this switch to "off" when the AJAX script updates ...

Creating a node.js function that can be used with OracleDB

I'm currently delving into learning nodeJS, but I'm facing a roadblock and can't seem to figure out what's causing the issue. Even the Debugger isn't providing much help. Any assistance or guidance would be greatly appreciated. The ...

The process of extracting values from an HTML tag using Angular interpolation

I am working on an Angular application that has the following code structure: <p>{{item.content}}</p> The content displayed includes text mixed with an <a> tag containing various attributes like this: <p>You can find the content ...

What is the best way to retrieve JSON data in ReactJS through ExpressJS?

Exploring the realms of reactjs and expressjs, I am seeking guidance on how to extract data from reactjs and store it in a variable. My current achievement includes successfully executing res.send to display the data. app.get('*', (req, res) =& ...

The map displayed on google.com appears different from the one featured on our website

The integration of the JS for the Google map on our website is working smoothly without any issues. However, when I zoom into our address on google.com/maps, our Hotel is listed as "Hotel". On the map displayed on our website, there are only a few entries ...

What is the best way to conceal the button?

I'm working on a program that involves flipping cards and creating new ones using three components: App, CardEditor, and CardViewer. Within the CardEditor component, I am trying to implement a function that hides the button leading to CardViewer until ...

Ways to verify AJAX Response String when data format is specified as JSON

When using AJAX to retrieve JSON data from a webpage, it's essential to set the responseType to json. If the data processing is successful, a valid JSON string is returned, which works perfectly. However, if there's an error on the webpage, inst ...

What is the reason for jQuery returning an integer instead of an object?

Currently, I am attempting to preselect an option within a <select> tag based on a variable. However, while using jQuery to select the elements and iterating through them with .each(), it appears to be returning integers instead of objects, making .v ...

Can Jquery mobile detect drag gestures?

Is there an event in Jquery Mobile that allows you to hide/show a div by dragging it, similar to the effect seen on phones? I have searched on different platforms and found that using Jquery UI is the closest solution. Is it possible to achieve this only ...