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

The location layer on my Google Maps is not appearing

For a school project, I am working on developing a mobile-first website prototype that includes Google Maps integration. I have successfully added a ground overlay using this image, but I am facing issues with enabling the "my location layer". When I tried ...

Enhancing 2D video viewing with Threejs interactivity

I want to create an interactive 2D video using three.js and maintain the aspect ratio of the video when resizing the browser window. Here is the code I am currently using: var camera, scene, renderer; var texture_placeholder, distance = 500; init() ...

Tips for effectively grouping a JavaScript object array with the help of Lodash

I have an array of objects in JavaScript that looks like this: [{ day : "August 30th", id: 1, message : "lorem ipsum1" },{ day : "August 30th", id: 2, message : "lorem ipsum2" },{ day : "August 31th", id: 3, message : " ...

What is the best method to eliminate empty columns while retrieving dynamic data in ion segments?

I am facing an issue where the data fetched dynamically in ion-segment using Ng displays empty columns in the segments other than the first one, which is labeled as "ALL". For example, if the first segment fetches 5 items and the second segment fetches 3 i ...

Smooth scrolling problems arise when a page loads and the offset jumps unexpectedly when the ID and hash are set to the same value

UPDATE: I'm considering converting this to jQuery, similar to the example here: http://davidwalsh.name/mootools-onload-smoothscroll Situation: Working on a Wordpress site with subnav navigation set for smooth scrolling down the page using /page/#idna ...

Accessing data attributes using jQuery and the class selector

I'm looking for a way to trigger an onClick event for an entire class of elements and access their individual data attributes within the function. Typically, I would use the following method: $(".classy").click(function(){ console.log("Replace th ...

Utilize Jquery to send a preset value through an ajax request

I am working on a select box functionality where the selected option is sent via ajax to a server-side script. The current setup is functioning properly. Here is the code for the select box: <select id="main_select"> <option selecte ...

jqGrid - Error when the length of colNames and colModel do not match!

Whenever I implement the code below, it triggers an error saying "Length of colNames and <> colModel!" However, if isUserGlobal is false, no errors occur. The version of jqGrid being used is 4.5.4 receivedColModel.push({name:'NAME', index: ...

How can the entire menu be closed in Bootstrap 5 when clicking on a link or outside of the page?

I'm currently utilizing BootStrap 5 for constructing my webpage. Within my page, I have a NavBar Menu containing various links. <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Error with JavaScript slideshow The slideshow using JavaScript seems to

I'm currently utilizing a script from the WOW Slider (free version) that looks like this: var slideIndex = 0; function showSlides() { var i; slides = document.getElementsByClassName("mySlides"); dots = document.getEle ...

Socket.io is most effective when reconnecting

I am currently in the process of developing a React application that connects to a Node.js API and I am trying to integrate the Socket.io library. Following various online tutorials, my code now looks like this: API: import express from 'express&apo ...

"Is it possible to load the jQuery dform plugin from a JSON file

I have been using the JQuery dForm plugin to construct a form and it has been functioning well with the provided code snippet: $("#myform").dform({ "action" : "index.html", "method" : "get", "html" : [ ...

Transform into dynamic types in Java

Today, I'm facing a challenge with JSON data that consists of an array of objects. Each object in the array contains two properties: type and value. [{ "type": "Boolean", "value": false }, { "type": "String[]", "value": ["one", "two", ...

Verify that the text entered in the form is accurate, and if it meets the required criteria, proceed to the next

Is it possible to achieve this without using JavaScript? If not, I'd like to find the simplest solution. I have a form that functions similar to a password entry field, and I would like to redirect users to a certain page if they type in a specific p ...

Stream JSON data to a file with Node.js streams

After reading this article, I decided to utilize the fs.createWriteStream method in my script to write JSON data to a file. My approach involves processing the data in chunks of around 50 items. To achieve this, I start by initializing the stream at the be ...

Testing for the presence of a child element within a parent component in React

Below is the structure of my component: const Parent = (props) => { return <div>{props.children}</div>; }; const Child1 = (props) => { return <h2>child 1</h2>; }; const Child2 = (props) => { return <h2>child 2 ...

Guide to attaching a mouse click event listener to a child element within a Polymer custom component

I'm currently facing an issue where I am attempting to attach a click listener to one of the buttons within a custom element during the "created" life cycle callback (even attempted using the "ready" callback with the same outcome). Unfortunately, I ...

What are some React component libraries compatible with Next.js 13.1?

I'm exploring Next.js and experimenting with version 13.1 and the new app directory. Is it feasible to accomplish this without sacrificing the advantages of server controls? An error message I encountered states: You're attempting to import a c ...

Tips for making SoapUI json requests compatible with German umlauts

In our team project, we heavily rely on SoapUI for handling various interfaces. Recently, we encountered an issue related to German special characters known as umlauts. When attempting to send a POST request with a Json body containing a German umlaut, we ...

Unable to delete React element by ID as it is undefined

Having some trouble deleting an item by ID with React. Despite the backend routes functioning properly (node and postgresql), every attempt to delete an item results in it reappearing upon page refresh. The command line indicates that the item being delete ...