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!
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Getting Started with Express
- How to Set Up Cron Jobs in Linux
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Setting Up Stylus CSS Preprocessor
- Using Axios to Pull Data from a REST API