Javascript – Generate HTML page with JS from JSON

htmljavascriptjsonparsing

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.

Best Answer

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>