Languages
[Edit]
EN

JavaScript - beautify JSON

4 points
Created by:
telsa
502

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

Alternative titles

  1. JavaScript - print pretty JSON
  2. JavaScript - pretty formating for JSON
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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