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:
// ONLINE-RUNNER:browser;
function beautifyJson(json) {
var object = JSON.parse(json);
return JSON.stringify(object, null, 4); // 4 spaces as indent
}
// Usage example:
var uglyJson = '{"id": 2, "name": "Tom", "age": 25}';
var beautyJson = beautifyJson(uglyJson);
console.log(beautyJson);
Beauty JSON with tab indents example
It is necesary just to change last argument of stringify()
method to '\t'
.
// ONLINE-RUNNER:browser;
function beautifyJson(json) {
var object = JSON.parse(json);
return JSON.stringify(object, null, '\t'); // tabulator as indent
}
// Usage example:
var uglyJson = '{"id": 2, "name": "Tom", "age": 25}';
var beautyJson = beautifyJson(uglyJson);
console.log(beautyJson);