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!
- Getting Started with TypeScript
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- Learn how to build a Slack Bot using Node.js
- Setting Up a Local Web Server using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript