DEV Community

Cover image for JavaScript built-in & beautify JSON
undqurek
undqurek

Posted on • Edited on • Originally published at dirask.com

JavaScript built-in & beautify JSON

Do you know the best way how to beautify JSON in pure JavaScript?
As answer: now I know?
But in the past it wasn't obvious.
I have used online tools.
Today, I know quick solution:

const beautifyJson = (json) => {
    var object = JSON.parse(json);
    return JSON.stringify(object, null, 4); // 4 spaces as indent
}

// Usage example:

const uglyJson = '{"id": 2, "name": "Tom", "age": 25}';
const beautyJson = beautifyJson(uglyJson);

console.log(beautyJson);
Enter fullscreen mode Exit fullscreen mode

Online runnable examples: https://dirask.com/posts/pqqJxp

Top comments (0)