I am trying to use mustache with a bootstrap calendar called Bic_Calendar basically you can add events to the calendar with an object like this
var events = [
{
date: "28/10/2013",
title: 'DUE DAY ENROLMENT',
},
{
date: "29/10/2013",
title: 'DUE DAY PAYMENT',
},
{
date: "31/10/2013",
title: '1st DAY OF CLASS',
},
]
;
what I want is using mustache to have a quick summary of the next events, the problem is that in order to mustache render the template the object needs to be change to:
var events = {"events": [
{
date: "28/10/2013",
title: 'DUE DAY ENROLMENT',
},
{
date: "29/10/2013",
title: 'DUE DAY PAYMENT',
},
{
date: "31/10/2013",
title: '1st DAY OF CLASS',
},
]}
;
so I am trying to concatenate the original event into a new one but it is not working, so i guess i am doing something wrong in the concatenation
var events1 = '{"events": '. concat(events) .concat('}');
var events1 = '{"events": ' + events + '}';
non of this options works!
var events
is not JSON. It is a literal javascript array, you should not be concatenating it, but simply nesting it in a new object and then serializing into JSON if you need a JSON string.
var events = [
{
date: "28/10/2013",
title: 'DUE DAY ENROLMENT',
},
{
date: "29/10/2013",
title: 'DUE DAY PAYMENT',
},
{
date: "31/10/2013",
title: '1st DAY OF CLASS',
},
];
var nestedEvents = { 'events': events };
var jsonEvents = JSON.stringify(nestedEvents);
As a general rule of thumb, if you find yourself tempted to manually build a JSON string, you are probably not taking the right approach. Build the data structure you want to serialize into JSON first, then serialize it.
The other takeaway, which seems to be a common point of confusion for developers, is that JSON is nothing more than a serialized string representation of some data structure. There is no such thing as a JSON object. The JSON format certainly bears a strong resemblance to a javascript object literal, but it is truly different and should be treated as such. In this case your events
variable does not contain a JSON string, so you should not expect to be able to concatenate it as if it were a string.