Combining various Google calendar feeds into a single JSON object using JavaScript

I'm currently in the process of integrating JSON feeds from multiple Google calendars to organize upcoming events and showcase the next X number of events in an "Upcoming Events" list.

While I initially achieved this using Yahoo! Pipes, I aim to eliminate reliance on third-party aggregators. Despite being close, I'm encountering challenges with creating the JSON objects correctly. The data gets stored in an array, but not in JSON format, hindering manipulation.

Attempts like

var myJsonString = JSON.stringify(JSONData);
with https://github.com/douglascrockford/JSON-js proved error-prone, possibly due to the variable's incorrect initial format. Likewise, simple feed calls such as $.getJSON(url); coupled with a function like function concant1() to perform JSONData=JSONData.concat(data); do not execute, leading to likely similar outcomes. Various other methods tried yield mixed results. Here's the closest I've gotten:

var JSONData = new Array();
var urllist = ["URL1","URL2","URL3"];

urllist.forEach(function addFeed(url){
    alert("Using URL: "+ url);
    if (void 0 != JSONData){JSONData=JSONData.concat($.getJSON(url));}
    else{JSONData = $.getJSON(url);}
    alert("The count from concatenated JSONData: "+JSONData.length); 
});

document.write("Final JSONData count: "+JSONData.length+"<p>");
console.log(JSONData)

UPDATE: Now fully functional source code!! :) Suggestions for enhancing code efficiency are welcome. I hope this proves helpful to others.:

// GCal MFA - Google Calendar Multiple Feed Aggregator
// Usage: GCalMFA(CIDs,n); 
// Where 'CIDs' represents comma-separated Google calendar IDs like <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="731a173314011c06035d10121f161d1712015d141c1c141f165d101c1e">[email protected]</a>, and 'n' indicates the number of results to display.
// Eliminate this error-checking code for IE, and the console.log statements if not required for regular use
// Author: Jeramy Kruser - http://jeramy.kruser.me

// Add a tag to your page to identify it as js-enabled for CSS purposes
document.body.className += ' js-enabled';

// Global variables
var urllist = [];
var maxResults = 3; 
var JSONData = {};
var eventCount = 0;

// Prototype forEach necessary for IE
if ( !Array.prototype.forEach ) {
  Array.prototype.forEach = function(fn, scope) {
    for(var i = 0, len = this.length; i < len; ++i) {
      fn.call(scope, this[i], i, this);
    }
  }
}

// Function to parse dates
function parse (str) {
    str = str.match (/^(\d{4})(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])$/);
    if (str) {
       str[0] = new Date ( + str[1], + str[2] - 1, + str[3]);
       if (str[0].getMonth () === + str[2] - 1) {
          return str[0];
          }
    }
    return undefined;
 }

// Function for HTML output
function output() {
    // For output HTML
}

// Function for sorting events
function sortFeed(event) {  
    // For sorting events
}

// Function to complete aggregation
function complete(result) {
    // Complete aggregation
}

// Main function for multiple feed aggregation
function GCalMFA(list,results){
    // Main function
}

Answer №1

Alright, let me break down the key changes that need to be implemented.

Updated jsFiddle: http://jsfiddle.net/ynuQ5/2/

Avoid using concat on the return value of $.getJSON. As previously mentioned, this will give you the XMLHttpRequest object, which is more than just the data you need. It's important to handle this in the callback for the AJAX request instead, by updating your URL list to include &callback=?, initializing the JSONData variable to match the structure in your 2nd screenshot, and modifying the AJAX request javascript like so:

var JSONData = { count: 0,
    value: {
        description: "Calendars from the Unitarian Universalist Association (UUA.org)",
        generator: "StackOverflow communal coding",
        items: []
}};

// URL list declaration goes here

urllist.forEach(function fetchFeed(url){
    $.getJSON(url, function(result) {
        if(!result.feed.entry) {
            console.log("No entries from " + url);
            return;
        }
        JSONData.count += result.feed.entry.length;
        JSONData.value.items = JSONData.value.items.concat(result.feed.entry);
        console.log(JSONData);
    });
});

You might notice some differences between the raw data from Google and the transformed data from the Yahoo pipe. Google provides object structures while Yahoo returns text values. For example, Google's data looks like this:

id: Object
    $t: "http://www.google.com/calendar/feeds/5oc3kvp7lnu5rd4krg2skcu2ng%40group.calendar.google.com/public/full/bbidp5qb4vh5vk9apok1cpnino_20130119"
link: Array[2]
    0: Object
        href: "https://www.google.com/calendar/event?eid=YmJpZHA1cWI0dmg1dms5YXBvazFjcG5pbm9fMjAxMzAxMTkgNW9jM2t2cDdsbnU1cmQ0a3JnMnNrY3UybmdAZw"
        rel: "alternate"
        title: "alternate"
        type: "text/html"
    1: Object
    length: 2
published: Object
    $t: "2012-11-13T15:59:31.000-05:00"
title: Object
    $t: "30 Days of Love"
    type: "text"
updated: Object
    $t: "2012-11-13T15:59:31.000-05:00"

On the other hand, Yahoo's data is more simplistic:

id: "http://www.google.com/calendar/feeds/5oc3kvp7lnu5rd4krg2skcu2ng%40group.calendar.google.com/public/full/bbidp5qb4vh5vk9apok1cpnino_20130119"
link: "href: "https://www.google.com/calendar/event?eid=YmJpZHA1cWI0dmg1dms5YXBvazFjcG5pbm9fMjAxMzAxMTkgNW9jM2t2cDdsbnU1cmQ0a3JnMnNrY3UybmdAZw"
published: "2012-11-13T15:59:31.000-05:00"
title: "30 Days of Love"
updated: "2012-11-13T15:59:31.000-05:00"

You can either transform the data upon receipt or adjust your display code to accommodate the raw values.

If you need further clarification on my code or response, feel free to ask.

Update: Check out the revised jsFiddle demonstrating how to access the author, start time, and title: http://jsfiddle.net/ynuQ5/8/. Let me know if you require more specific information :-)

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

Load components in NextJS lazily without utilizing `next/dynamic`

Currently, I am in the process of developing a component (Editor) that should always be lazy-loaded in React applications. However, I need it to be compatible with any React app. While I have successfully implemented lazy loading with Create React App usi ...

Convert the object into a neatly formatted JSON string using the Dump() function

Hey there, I'm currently facing a challenge and would prefer not to create my own solution if there is already one available with a permissive license. I am looking for a way to convert any object instance into a human-readable JSON string. Our origi ...

Launch a new Windows form upon clicking an HTML button using DotNetBrowser

I attempted to open a Windows form using the DotNetBrowser control with specific HTML content as shown in the code below. Upon clicking a button on the HTML page, I want to hide the loaded form and then display the second Windows form. Here is the C# cod ...

Troubleshooting: Issue with Chrome's CSV Export Functionality in JavaScript/AngularJS

Currently, I am troubleshooting an issue with exporting a CSV file from a data table on a web application. The export functionality works fine on all browsers except for Chrome when the export button is clicked. I have been trying to solve this problem for ...

Unable to load the node modules

In my development journey, I created an ASP.NET MVC project using Angular 2 in Visual Studio 2017 and set up node for package management. Here is a snippet from the package.json file: { "version": "1.0.0", "name": "asp.net", "private": true, ... ...

Difficulty with rendering a React component in a basic demonstration

I'm trying to display "Hi", but even though I'm not getting any errors, nothing is showing up on the screen. Can anyone assist with this issue? <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15. ...

Understanding the process of deserializing JSON data into multiple schemas using Json.NET

Recently, I've started working with JSON and I've managed to retrieve the following structure through an API call... { "Customers":[ { "Code":"11111", "Alpha":"A", "Name":"T ...

Is there a way to handle the completion event of jQuery's .tmpl() method?

Can someone guide me on how to create a $.tmpl ready function? In my code, I send the ajax json to my createForm function. var doFunction = { new: function() { $.ajax({ url: 'index.php?...', success: function(data) { cr ...

Unable to get onChange function to work with multiple input fields in React

I am attempting to implement a feature where an additional input field is added when the user clicks on the "Add input" button, and then store those input values in an object: const {useState } = React; const InviteUser = () => { const [userDetail ...

Transforming Form Input Fields into a Nested JSON Format with the Power of JQuery

I'm facing a challenge in converting the input fields below into a nested JSON file structure in my HTML page. Despite trying various methods, I haven't been successful yet. These inputs are retrieved through AngularJS ng-repeat. Any assistance o ...

AWS Amplify-hosted Nuxt applications are resilient to errors during the build process

My website is built using Nuxt js and hosted on AWS Amplify. I've encountered a major issue where the website still gets generated successfully even when there's a failure in the nuxt generate command (like a JavaScript error in my code). Below i ...

The npm outdated command seems to ignore the caret notation specified in the package.json file

When looking at a package.json file that contains the following: "devDependencies": { "grunt": "^0.4.5", "grunt-concurrent": "^1.0.0", "grunt-contrib-jshint": "^0.10.0", "grunt-contrib-watch": "^0.6.1", "grunt-dev-update": "^1.1.0", ...

Issue with Guild Member Add functionality in discord.js is not functioning as expected

I'm facing an issue with my code where the bot does not send a welcome message when a user joins, despite having everything set up correctly. Even when a user leaves, there is no farewell message being sent either. Here is the code I am using: bot.on ...

Send an array and a single string to a PHP script using an Ajax request

I am attempting to incorporate the code snippet below: var flag = new Array(); var name = $("#myselectedset").val(); $.ajax({ type: 'post', cache: false, url: 'moveto.php', data: {&a ...

What is the best way to save the outcomes of several asynchronous $.get calls into an array?

I have a challenge where I need to retrieve data from an API for each item in an array, and then store that data in another array for further processing. However, I suspect the issue lies in the asynchronous nature of the requests, as the data may not be ...

Retrieving the value of a submit button within the `onSubmit` event handler in a React application

In my usual process, I typically handle the form submission by utilizing the onSubmit handler. <form onSubmit={e => { ... } }> <input ... /> <input ... /> <button type="submit">Save</button> </form> ...

Has anyone successfully incorporated Load more pagination in an Android app using a JSON parser?

Attempting to add a load more pagination feature in android for my listview using JSON Parser. Came across a tutorial for XML parser here. Any suggestions on how to achieve this with JSON? ...

Trouble with Mongoose: Data Not Being Saved

I'm encountering difficulties with a basic query on my database. While following this tutorial at https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4, the author receives a JSON object containing the name field (the only custom fi ...

Unable to retrieve JSON data in Angular2 as expected

I am encountering an issue while attempting to retrieve data from a JSON file stored in my assets folder within Angular 2. The data is not displaying as expected despite my efforts. The JSON file I am trying to access is named: test.json [ "{'id ...

Use Node and Express with JavaScript to store HTML form data in JSON format within a .json file

Just starting out with node and express. I am capturing user input from an HTML form and attempting to append or push it in a .json file. I tried using the jsonfile npm package but the data is not being stored in an array format in the JSON file. Here is ...