Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  169] [ 6]  / answers: 1 / hits: 42603  / 12 Years ago, thu, march 8, 2012, 12:00:00

I'm looking for a very basic example of using Javascript to parse a JSON file and output an html file or populate an html file. All the examples I've located so far have code snippets and I don't have the background to fill in the blanks between.



Thank you for any fiddles (which would be awesome), links, and smart a*s comments.


More From » html

 Answers
1

You can use a microtemplating library, like Mustache, to parse incoming JSON objects into HTML snippets using {{ key }} template syntax. If your object looks like:



var myObj = {
name: 'Joe Smith',
age: 25,
features: {
hairColor: 'red',
eyeColor: 'blue'
}
};


Using Mustache, you can render it into HTML easily using {{#}} and {{/}} to traverse nested objects:



Mustache.render('Hello, my name is {{name}} and I am {{age}} years old. {{#features}} I have {{hairColor}} hair and {{eyeColor}} eyes.{{/features}}', myObj);


which outputs:



Hello, my name is Joe Smith and I am 25 years old. I have red hair and blue eyes.



EDIT: more germane application - dynamically generate a control panel using a template with nested lists of objects. Here's my template and object (HTML broken into a list and joined for clarity):



var panel = [
'<div id=cpanel>',
'{{#cpanel}}',
'<div class=panel_section>',
'<h1 class=cpanel>{{name}}</h1>',
'<p>',
'{{#content}}',
'<button id={{id}}>{{id}}</button>',
'{{/content}}',
'</p>',
'</div>',
'{{/cpanel}}',
'</div>',
].join('n');

var panelObj = {
cpanel: [
{
name: 'playback',
content: [
{id: 'play'},
{id: 'pause'},
{id: 'stop'}
]
}, {
name: 'zoom',
content: [
{id: 'zoomIn'},
{id: 'zoomOut'}
]
}]
};


Then you render with Mustache:



Mustache.render(panel, panelObj);


which outputs:



<div id=cpanel>
<div class=panel_section>
<h1 class=cpanel>playback</h1>
<p>
<button id=play>play</button>
<button id=pause>pause</button>
<button id=stop>stop</button>
</p>
</div>
<div class=panel_section>
<h1 class=cpanel>zoom</h1>
<p>
<button id=zoomIn>zoomIn</button>
<button id=zoomOut>zoomOut</button>
</p>
</div>
</div>

[#86969] Wednesday, March 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aleighabayleef

Total Points: 511
Total Questions: 99
Total Answers: 99

Location: Aruba
Member since Fri, Jun 24, 2022
2 Years ago
;