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
- Declare a JSON object and store it in the variable.
- Use JSON.stringify(obj) method to convert JavaScript objects into strings and display them.
- Use JSON.stringify(obj, replacer, space) method to convert JavaScript objects into strings in a pretty format.
Example 1: This example uses JSON.stringify() method to print the object element specifies <pre> tag.
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)); |
{"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.
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));
|
{"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.