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?
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, '&').replace(/\\"/g, '"')
.replace(/</g, '<').replace(/>/g, '>')
.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.
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});
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
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly