kitsune kitsune - 1 month ago 13
jQuery Question

Why JSON.stringify($('#calendar').fullcalendar('clientEvents')) fails?

As title, when I try to do:

myString = JSON.stringify($('#calendar').fullcalendar('clientEvents'));


it fails. I tried to alert
myString
but I see a series of
[Object object], ... .
But if i try to alert
myArray[0].title
for example, it returns correctly.

Where I'm doing wrong?

P.S. The goal is to obtain a string to save on a file via AJAX.

Answer

Your results tell you that the objects in the array that the fullCalendar clientEvents method gives you can't be directly converted to JSON. I get slightly different results on the http://fullcalendar.io page (I get an error about trying to convert a circular structure); I assume that's down to differences either in the FullCalendar version you're using vs. they're using, or differences in how your browser and mine deal with circular structures. Either way, the objects apparently can't be used as-is.

The goal is to obtain a string to save on a file via AJAX.

You can do that by using map on the array to get objects that can be converted to JSON successfully, whitelisting the properties you want (or blacklisting the ones you don't want).

Here's an example whitelisting the start, end, and title properties:

var json = JSON.stringify($("#calendar").fullCalendar("clientEvents").map(function(e) {
    return {
        start: e.start,
        end: e.end,
        title: e.title
    };
}));

Heres one blacklisting source and any property starting with _:

var json = JSON.stringify($("#calendar").fullCalendar("clientEvents").map(function(e) {
    var rv = {};
    Object.keys(e)
        .filter(function(k) {
            return k != "source" && !k.startsWith("_");
         })
        .forEach(function(k) {
            rv[k] = e[k];
        });
    return rv;
}));

...which worked for me on their site.

Here are ES2015 versions of both of those:

Whitelisting:

let json = JSON.stringify($("#calendar").fullCalendar("clientEvents").map(e => ({
    start: e.start,
    end: e.end,
    title: e.title
})));

Blacklisting:

let json = JSON.stringify($("#calendar").fullCalendar("clientEvents").map(e => {
    let rv = {};
    Object.keys(e)
        .filter(k => k != "source" && !k.startsWith("_"))
        .forEach(k => {
            rv[k] = e[k];
        });
    return rv;
}));
Comments