How to Pretty-print a JSON Object using JavaScript

Updated onbyAlan Morel
How to Pretty-print a JSON Object using JavaScript

JSON is the most common data format used in web applications because it is easy to read and write, and is space-efficient when compared to XML.

Thankfully, JavaScript makes working with JSON very easy because it comes with built-in functions that allow you to convert JSON into JavaScript objects and vice versa.

In this post, we'll learn how to pretty-print JSON objects using JavaScript.

JavaScript Pretty-Print a JSON Object

The best way to pretty print a JSON object is to use the built-in JSON.stringify() function. This function takes a JavaScript object and serializes it to return a string.

This method is used extensively in web development and is useful when you want to send JSON data to a server or client.

The function has three parameters, with only the first, the object itself, being required. The second parameter is an optional object that can be used to customize the output. The third parameter is the number of white spaces to indent the output.

Let's look use this example object:

JAVASCRIPT
const obj = { "name": "John", "age": 30, "cars": [ "Ford", "BMW", "Fiat" ] };

We can serialize this object using the JSON.stringify() function:

JAVASCRIPT
const obj = { "name": "John", "age": 30, "cars": [ "Ford", "BMW", "Fiat" ] }; const json = JSON.stringify(obj); console.log(json);
BASH
{"name":"John","age":30,"cars":["Ford","BMW","Fiat"]}

This is great, but maybe you want it to look more presentable. Let's use the second and third parameters to customize the output to have indentation:

JAVASCRIPT
const obj = { "name": "John", "age": 30, "cars": [ "Ford", "BMW", "Fiat" ] }; const json = JSON.stringify(obj, null, 4); console.log(json);
BASH
{ "name": "John", "age": 30, "cars": [ "Ford", "BMW", "Fiat" ] }

As you can see, this new output is much more readable which is the whole point of pretty-printing JSON.

Conclusion

In this post, we learned how to pretty-print JSON objects using JavaScript using the built-in JSON.stringify() function.

You can optionally pass it in parameters that will customize the output and indentation level.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.