Open In App

How to pretty print JSON string in JavaScript ?

Last Updated : 27 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In this article, we are going to learn how to pretty print JSON strings in JavaScript.

Approach

Example 1: This example uses JSON.stringify() method to print the object element specifies <pre> tag. 

Javascript




let obj = {
    "prop_1": {
        "prop_11": "val_11",
        "prop_12": "val_12"
    },
    "prop_2": "val_2",
    "prop_3": "val_3"
};
 
console.log(JSON.stringify(obj));
 
console.log(JSON.stringify(obj, undefined, 4));


Output

{"prop_1":{"prop_11":"val_11","prop_12":"val_12"},"prop_2":"val_2","prop_3":"val_3"}
{
    "prop_1": {
        "prop_11": "val_11",
        "prop_12": "val_12"
    },
    "prop_2": "val_2",
    "prop_...

Example 2: This example is a bit similar to the previous one but it specifies the properties to print the object of the object. It also takes advantage of JSON.stringify() method to print an object within <pre> element. 

Javascript




let obj = {
    "prop_1": {
        "prop_11": "val_11",
        "prop_12": "val_12"
    },
    "prop_2": "val_2",
    "prop_3": "val_3"
};
 
console.log(JSON.stringify(obj));
 
console.log(JSON.stringify(obj,
        ['prop_2', 'prop_3'], 4));


Output

{"prop_1":{"prop_11":"val_11","prop_12":"val_12"},"prop_2":"val_2","prop_3":"val_3"}
{
    "prop_2": "val_2",
    "prop_3": "val_3"
}

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads