3

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?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Michael Pell
  • 1,416
  • 1
  • 14
  • 17

1 Answers1

9

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]));
}
Community
  • 1
  • 1
Jefferey Cave
  • 2,507
  • 1
  • 27
  • 46