EN
JavaScript - beautify JSON
4 points
In this short article we would like to show how in simple way beautify JSON using built-in JavaScript solutions.
Quick solution:
xxxxxxxxxx
1
function beautifyJson(json) {
2
var object = JSON.parse(json);
3
return JSON.stringify(object, null, 4); // 4 spaces as indent
4
}
5
6
// Usage example:
7
8
var uglyJson = '{"id": 2, "name": "Tom", "age": 25}';
9
var beautyJson = beautifyJson(uglyJson);
10
11
console.log(beautyJson);
It is necesary just to change last argument of stringify()
method to '\t'
.
xxxxxxxxxx
1
function beautifyJson(json) {
2
var object = JSON.parse(json);
3
return JSON.stringify(object, null, '\t'); // tabulator as indent
4
}
5
6
// Usage example:
7
8
var uglyJson = '{"id": 2, "name": "Tom", "age": 25}';
9
var beautyJson = beautifyJson(uglyJson);
10
11
console.log(beautyJson);