Languages
[Edit]
EN

JavaScript - beautify JSON

4 points
Created by:
Marcin
18610

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);

JavaScript - JSON

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join