How to Pretty-print a JSON Object using JavaScript
Table of Contents
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:
JAVASCRIPTconst obj = {
"name": "John",
"age": 30,
"cars": [
"Ford",
"BMW",
"Fiat"
]
};
We can serialize this object using the JSON.stringify()
function:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Setting Up a Local Web Server using Node.js