Parsing JSON using Javascript

The quickest and simplest way to render JSON in the browser is to use JSON.stringify( ).

Your code would look very much like this:

  1. var json = {a:1,b:2,c:3};
  2. var text = JSON.stringify(json);
  3. document.body.innerHTML = meep;

Obviously that’s with no formatting and uses the entire page to show you a string of JSON, but your requirement was simply to output JSON from a rest API.

If you’re actually trying to format the JSON to look pretty and render it to the page, I would recommend one of the following libraries:

  • Mustache.js: Simple templating framework that uses html style syntax
  • Handlebars.js: Similar to mustache but with conditional statements and loops
  • Hogan.js: Same syntax as mustache but precompiles templates and is one of the fastest templating libraries
  • Underscore.js: Has a templating function built in. Can be configured to use a custom syntax for defining interpolation points. I recommend defining a variable in your templateSettings (_.templateSettings.variable = x) as it will improve performance. The standards settings use the¬†with¬†operator which can result in reduced performance.

admin has written 55 articles