How to Pretty Print JSON String in JavaScript?
Last Updated :
17 Nov, 2024
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.
We can use JSON.stringify() method to pretty print the object element or JSON string in JavaScript. We can pass the object or string to the JSON.stringify() method and it will return the pretty print JSON string.
Syntax
JSON.stringify( obj );
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_...
We can use JSON.stringify(obj) method to convert JavaScript objects into strings. Declare a JSON object and store it in the variable. Use the JSON.stringify(obj, replacer, space) method to convert JavaScript objects into strings in a pretty format.
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"
}