Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Mustache.js to Embed Raw JSON

Tags:

mustache

I am using mustache on the command line to embed a JSON object inside of <script> tags within an HTML object.

cat sampleData.json | mustache - man_report.mustache > output.html

Sample data looks like this:

{"report_type":"total_by_age_group",
"data":[{"age_group":"Age 41 - 65","percent":41.04},
        {"age_group":"Age Over 66","percent":19.11},
        {"age_group":"Age < 18 Or Invalid Birth Date","percent":0.00},      
        {"age_group":"Age 18 - 25","percent":8.03},
        {"age_group":"Age 26 - 40","percent":31.82}]}

Which is what I would like to also see in the resultant HTML file.

report.mustache looks like:

reportObject = {{data}}

output.html looks like this:

reportObject = [object Object],[object Object],[object Object],[object Object],[object Object]

I just want the exact same JSON as I started with. Any ideas?

like image 286
Michael Pell Avatar asked Apr 26 '26 18:04

Michael Pell


1 Answers

A little bit old, but this was the first question that came up when I did a search. I found an answer here: https://stackoverflow.com/a/15580946/1961413

If you are able to preprocess the data, you could stringifiy it. This would make it a string that could be embedded:

var sampleData = JSON.stringify(sampleData);

Once you've done this you need to ensure that Mustache doesn't HTMLize the string (triple up the handlebars):

var reportObject = {{{.}}};

You can then access it in you webpage:

alert(reportObject.report_type);
for($data in reportObject.data){
     alert(JSON.stringify(reportObject.data[$data]));
}
like image 139
Jefferey Cave Avatar answered May 03 '26 04:05

Jefferey Cave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!