The use of JSON.parse does not support parsing URL links

As a junior developer specializing in Javascript and Google Apps Script, I decided to enhance the functionality of my Google Sheets by tracking the last modification time of URLs stored in them. Although I attempted to create a script for this task, it seems that I may need some professional guidance.

The goal is to loop through a column containing around 2500 URLs and display each URL's modified date (extracted from its metadata) in an adjacent cell. Below is the code I have written:

    function iteration1() {
        var ss = SpreadsheetApp.getActiveSpreadsheet();
        **//The list to iterate on.**
        var sheet = ss.getSheetByName("Fund List");
        **//The column of which the links are stored**
        var urls = sheet.getRange("D2:D150").getValues();

        for (var row = 0; row < urls.length; row++) {
            for (var col = 0; col < urls[row].length; col++)
                **//Varifying if there is a URL within the cell**
                if (urls[row][col] != '') {
                    **//Storing each URL in a new array**
                    var url = UrlFetchApp.fetch(urls[row][col].valueOf());
                    **//Parsing the meta-data of the URL into an array**
                    var tweets = JSON.parse(url);
                    **//Retrieve the link modification date from the meta-data array & outputs to the cell from the right respectivley.**
                    sheet.getRange(row+2, 13).setValue(Logger.log(tweets[4][2]).getLog());
            }
        }
    }

For instance, consider the following link

Its metadata includes:

{Accept-Ranges=bytes, X-Robots-Tag=noindex, nofollow, noarchive,nosnippet, Cache-Control=max-age=604800, Server=Microsoft-IIS/7.0, ETag="01827159b1d11:0", Access-Control-Allow-Origin=*, Access-Control-Allow-Methods=GET,PUT,POST,DELETE,OPTIONS, Last-Modified=Wed, 18 May 2016 23:00:00 GMT, Content-Length=113029, Access-Control-Allow-Headers=Content-Type, Date=Thu, 01 Sep 2016 11:43:52 GMT, Content-Type=application/pdf}

I am specifically interested in extracting only the 'Last-Modified' field from this metadata array and displaying it in the adjacent cell.

Thank you in advance for any assistance provided! This community has been incredibly helpful!

I have also attached a screenshot showcasing my current code and the debugger mode illustrating the sample links I am working with: https://i.stack.imgur.com/bWUD3.jpg

Answer №1

Upon reviewing the information on Google's documentation ( https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String) ), it appears that the data stored in the variable url is not in string format.

The function JSON.parse expects a string input to convert it into a JavaScript Object, Array, String, or other data type.

To correct this issue, you should replace JSON.parse(url) with JSON.parse(url.getContentText('utf-8')) as specified in the documentation here: https://developers.google.com/apps-script/reference/url-fetch/http-response

Answer №2

It took me a few days of dedicated work, but I finally succeeded in extracting the Last-Modified date value for each URL in my spreadsheet.


Here is the code I used:

function iteration1() { 
  var ss = SpreadsheetApp.getActiveSpreadsheet();
    //Accessing the Google sheet
    var sheet = ss.getSheetByName("Sheet Name");
    //Fetching the array of URLs to check
    var urls = sheet.getRange("D2:D150").getDisplayValues();

    for (var row = 0; row < urls.length; row++) {
      for (var col = 0; col < urls[row].length; col++) {
        if (urls[row][col].toString() != '') {
          //Converting each URL to string and getting its Properties into a new Array
          var url = UrlFetchApp.fetch(urls[row][col].toString());
          var tweets = url.getAllHeaders();

          //Creating an array of Properties by Keys & Values
          var userProperties = PropertiesService.getUserProperties();
          userProperties.setProperties(tweets);
          var tweetsKeys = Object.keys(tweets);
        }
      }

      //Extracting the modification date from the property meta-data & setting it as a String in the respective cell.
      sheet.getRange(row+2, 12).setValue(userProperties.getProperty(tweetsKeys[7]));
    }
}

Big thanks to everyone who helped out!

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

Converting json file data into a case class using Spark and Spray Json

In my text file, I have JSON lines with a specific structure as illustrated below. {"city": "London","street": null, "place": "Pizzaria", "foo": "Bar"} To handle this data in Spark, I want to convert it into a case class using the Scala code provided be ...

Who is the father of Bootstrap Popover?

I'm currently facing an issue with getting a popover to be placed within a specific element. As of now, the popover is being inserted directly into the <body>, but I require it to be relative to other elements. I have been unable to locate a met ...

Having trouble passing data between view controllers

In my AngularJS application, I have a table column in main.html that is clickable. When clicked, it should redirect to a new customer page with the value of the column cell as the customer's name. There is a corresponding service defined for the app m ...

Confirming whether the digit entered in jQuery is a number

My website has a user input field where numbers are expected to be entered. I wanted to find a convenient way to validate the input using jQuery. After some research, I discovered jQuery's built-in function called isDigit. This handy function allows ...

Differences between Array and Database Search

Currently, I have implemented a system where I store a refresh token in a JavaScript array as well as in each user's information table. When a user requests data, I first check the token in the array. If the token matches one in the array, I loop thro ...

Displaying svg files conditionally in a react native application

I have developed an app specifically for trading dogs. Each dog breed in my app is associated with its own unique svg file, which are all stored in the assets folder (approximately 150 svg files in total). When retrieving post data from the backend, I re ...

Removing a faded out div with Vanilla JavaScript

I am struggling with a JS transition issue. My goal is to have the div automatically removed once it reaches opacity 0. However, currently I need to move my mouse out of the div area for it to be removed. This is because of a mouseleave event listener that ...

Failure to trigger the success action in ExtJS

I am currently utilizing struts2 for the server-side implementation combined with ExtJS4 for the user interface. I have a basic form that I submit to the server, but the response consistently goes to the failure case of the request even though I am just re ...

Why isn't v-model functioning properly in Vue?

In my current project involving an API, I encountered a problem. I utilized axios to fetch data from the API, which returned a JSON array. Each array item had a radio value that I appended to it. Despite attempting to use v-model to track changes in the ra ...

Developing a collection of reusable components in a Javascript bundle for enhanced efficiency

I currently have a backend rendered page (using Django) that I want to enhance by incorporating components from PrimeVue and a markdown editor wrapped as a Vue component. Previously, we utilized some simple animations with jQuery which we included directly ...

What is the best way to retrieve the value of an nth column in a table using

Is there a way to retrieve the value of a specific column in a table? For example, I want to get the value of the 2nd column. I have no trouble getting the first one using this method - it works perfectly fine. However, when I try to retrieve the value of ...

What is the best method for returning the AJAX outcome to the JSP page?

Using AJAX, I am able to post data from my JSP page to my servlet. $.ajax({ url: 'myServlet?action=FEP', type: 'post', data: {machine: i, name: txt}, // where i and txt hold certain values success: f ...

Leveraging grunt-develop

I have recently developed a basic NodeJS + Express application that runs smoothly when I use the command node app.js. However, my current task is to incorporate grunt-develop into my project. Here is how I configured it: grunt.initConfig({ develop: { ...

Set up specific vue.config.js configurations for unique environments in Vue

I am working on a multi-page app where I want certain pages to only show up in my development environment. Here's how my vue.config.js looks: module.exports = { productionSourceMap: false, pages: { index: "src/main.js", admin: { ...

PHP Form encountering error due to JSON decoding following an AJAX request

After extensive research and much confusion, I have finally decided to seek help here. I am able to make my AJAX request post successfully in every format except JSON. I am eager to understand JSON so that I can start using it right away instead of learni ...

remain on the multi drop down page for a specified duration

I have created a dropdown menu with a second level drop-down page that is a form. Now, I want the second level drop-down page to stay open longer, so I have used the following JavaScript code: <script> var timer; $(".parent").on("mouseover", functio ...

Alter the Vue view using an object instead of the url router

Currently working on a chrome extension using Vue.js where I need to dynamically update views based on user interactions. Usually, I would rely on the Vue Router to handle this seamlessly... however, the router is tied to the URL which poses limitations. ...

Moving a row from one Jquery Datatable to another table

I'd like to merge the rows from table 2 into table 1. If I check a row in the checkbox column and click on "add user," that row will be added to table 1. Next to the "add user" button, there is an option to select all or none. If I click on "select ...

Struggling to access specific data within a JSON object? Wondering how to extract and display data from a JSON object in VUE?

Despite my extensive searching on Stack and the internet, I have not been able to find a solution to my problem. Currently, I am attempting to retrieve data from a JSON file located in the Vue src folder. The file contains three arrays with names that inc ...

The watch functionality is failing to work within a specialized attribute directive that is being utilized within a separate custom element directive

I'm currently working with two directives that handle separate functionalities. I am attempting to utilize the attribute directive within an element directive, but I'm encountering issues with the watch function not working on the attribute direc ...