Skip to content

Instantly share code, notes, and snippets.

@QasimTalkin
Created June 5, 2022 13:51
Show Gist options
  • Select an option

  • Save QasimTalkin/0b973e88e77ad2e6233873fdadb72bf7 to your computer and use it in GitHub Desktop.

Select an option

Save QasimTalkin/0b973e88e77ad2e6233873fdadb72bf7 to your computer and use it in GitHub Desktop.
Print Json In HTML With Colors

Colorful JSON in HTML

JSON can very easily be translated into JavaScript. JavaScript can be used to make HTML in your web pages.

HTML

<pre><code id=account></code></pre>
<pre><code id=planets></code></pre>

CSS

pre {
   background-color: ghostwhite;
   border: 1px solid silver;
   padding: 10px 20px;
   margin: 20px; 
   }
.json-key {
   color: brown;
   }
.json-value {
   color: navy;
   }
.json-string {
   color: olive;
   }

JS

if (!library)
   var library = {};

library.json = {
   replacer: function(match, pIndent, pKey, pVal, pEnd) {
      var key = '<span class=json-key>';
      var val = '<span class=json-value>';
      var str = '<span class=json-string>';
      var r = pIndent || '';
      if (pKey)
         r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
      if (pVal)
         r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';
      return r + (pEnd || '');
      },
   prettyPrint: function(obj) {
      var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
      return JSON.stringify(obj, null, 3)
         .replace(/&/g, '&amp;').replace(/\\"/g, '&quot;')
         .replace(/</g, '&lt;').replace(/>/g, '&gt;')
         .replace(jsonLine, library.json.replacer);
      }
   };

var account = { active: true, codes: [48348, 28923, 39080], city: "London" };
var planets = [{ name: 'Earth', order: 3, stats: { life: true, mass: 5.9736 * Math.pow(10, 24) } }, { name: 'Saturn', order: 6, stats: { life: null, mass: 568.46 * Math.pow(10, 24) } }];
$('#account').html(library.json.prettyPrint(account));
$('#planets').html(library.json.prettyPrint(planets));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment