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?
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
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
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