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
1
: 4813 At:- 11/23/2017 6:56:47 AM
javascript Formatted-JSON pretty-print-JSON javascript pretty print json in html







3 Answers
profileImage Answered by:- vikas_jk

Quick and easy way to show formatted(pretty-print) JSON in javascript is to use JSON.stringify() in Javascript code

var jsonObj = {"Name": "Vikas", "city": "Paris 07",  "postalCode": "75007", "countryCode": "FRA",  "countryLabel": "France" };

document.getElementById("before").innerHTML = JSON.stringify(jsonObj);

document.getElementById("after").innerHTML = "<pre>"+JSON.stringify(jsonObj,undefined, "\t") +"</pre>"

here is the working fiddle: https://jsfiddle.net/3kc7oq8t/

OR

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,Thanks.

1
At:- 11/24/2017 7:11:08 AM Updated at:- 12/12/2022 4:52:27 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


profileImage Answered by:- bhanu

You can also use console.dir to pretty-print JSON in Browser console, here is the sample code

var jsonString='{"name":"John", "age":31, "city":"New York"}';
const object = JSON.parse(jsonString);

console.dir(object, {depth: null, colors: true});
1
At:- 5/8/2021 10:13:24 AM


profileImage Answered by:- vikas_jk

I would like to add another method here for formatting JSON

console.table(["apples", "oranges", "bananas"]);

It will output JSON in table format in your browser console.

You can also try this online tool Online JSON Beautifier (JSON Formatter) / JSON Format checker

0
At:- 1/18/2021 3:27:49 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