
Pretty JSON example
So many time we required ti print the JSON in pretty format because it is easy to read and understood. As we know JSON (JavaScript object notation) is a lightweight data-interchange format. It is easy for humans to read and write.
In this article you will learn how to print JSON in pretty format at browser.
Here is the CSS code create a new css file named as stylesheet.css.
stylesheet.css
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
pre {
background-color: #f8f8ff;
border: 1px solid #C0C0C0;
padding: 10px 20px;
margin: 20px;
}
.json-key {
color: #A52A2A;
}
.json-value {
color: #000080;
}
.json-string {
color: #556b2f;
}
|
I have used CSS for highlighting the key, value and strings.
Here is the JavaScript and HTML code to print the JSON in pretty format.
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<script>
$(function () {
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 products = { status: true, statusCode:200, message:"Products Listing", data: { products: [{ name: "Mobile", brand: "Samsung" }, { name: "Laptop", brand: "Dell" }, { name: "Sports Shoes", brand: "Campus" }], categories: ["Electronics","Footwear"] } };
$('#products').html(library.json.prettyPrint(products));
});
</script>
<pre><code id=products></code></pre>
|
Here in JavaScript I have cerated a function to make the JSON in pretty format. Here we have a products JSON and we are printing products JSON in pretty format. ...