My goal is to utilize JSON data for parsing a template using JavaScript. The Mustache library provides a solution as shown below:
var output = $("#output");
// template stored in JS var as a string
var templateString = '<div>'+
'<ul>'+
' <li>{{first_name}} {{last_name}} goes by the username of: {{user_name}}</li>'+
'</ul>'+
'</div>';
// parse template stored in JS string var
var html = Mustache.render(templateString, jsonData);
output.append(html);
The issue at hand is that the JSON data I have does not conform to the required format for Mustache templates.
The expected JSON format by Mustache is as follows:
var jsonData2 = {
"users":[
{
"id":"1",
"user_name":"jasondavis",
"first_name":"Jason",
"last_name":"Davis",
"is_admin":"1",
"gravatar_id":"http:\/\/www.gravatar.com\/avatar\/31b64e4876d603ce78e04102c67d6144?s=80&d=identicon&r=PG",
"gravatar_url":"http:\/\/www.gravatar.com\/avatar\/31b64e4876d603ce78e04102c67d6144?s=80&d=identicon&r=PG"
},
{
"id":"1702c3d0-df12-2d1b-d964-521becb5e3ad",
"user_name":"Jeff",
"first_name":"Jeff",
"last_name":"Mosley",
"is_admin":"1",
"gravatar_id":"http:\/\/www.gravatar.com\/avatar\/5359bf585d11c5c35602f9bf5e66fa5e?s=80&d=identicon&r=PG",
"gravatar_url":"http:\/\/www.gravatar.com\/avatar\/5359bf585d11c5c35602f9bf5e66fa5e?s=80&d=identicon&r=PG"
}
]};
Adjustments need to be made to the JSON data format to align with the Mustache template structure.
For more details and a demo, visit: http://jsfiddle.net/utgrLw96/25/