Languages
[Edit]
EN

JavaScript - beautify JSON

4 points
Created by:
Marcin
15740

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);
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join