How to show formatted (pretty-print) JSON using JavaScript?


I am getting a JSON from the server side(C# .NET) using jQuery ajax call, now I would like to show this JSON to users in readable format like postman does when we send request using it(& get results in JSON) or you can say want to show JSON in readable or formatted form.

How can I achieve it using jquery or javascript?


Asked by:- Vinnu
0
: 609 At:- 11/23/2017 6:56:47 AM
javascript Formatted-JSON pretty-print-JSON javascript pretty print json in html






1 Answers
profileImage Answered by:- vikas_jk

If your JSON is validated then you can implement code below to show pretty-print (formatted) version of JSON in your HTML

Javascript:

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 planets = [{ name: 'Earth', order: 3, date:'19/07/2017', 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));

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

You can check the working fiddle here

The above method is used to show formatted JSON programmatically, while the quick and easy solution is to use JSON.stringify()

JSON.stringify(jsObj, null, "\t"); //output formatted JSON, while jsObj is JSON

here is the working fiddle

1
At:- 11/24/2017 7:11:08 AM
I wasn't aware that even JSON.Stringify beautify json after taking arguments 0
By : Vinnu - at :- 11/24/2017 12:19:03 PM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly