Using Mustache.js to Embed Raw JSON

爱⌒轻易说出口 提交于 2019-12-10 10:19:36

问题


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?


回答1:


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]));
}


来源:https://stackoverflow.com/questions/34721836/using-mustache-js-to-embed-raw-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!