In JavaScript, you can use the JSON.stringify() method to convert JSON objects to their string representation, and this method also enables you to print JSON data in a highly readable format. JSON.stringify() accepts three parameters: the object to serialize, an optional replacer function, and an optional number or string to control indentation.
Here is an example demonstrating how to use the JSON.stringify() method to pretty-print a JSON object:
javascript// Assume we have the following JSON object const myObject = { name: "John", age: 30, cars: ["Ford", "BMW", "Fiat"] }; // The third parameter controls indentation, with 2 indicating two spaces per level const prettyJson = JSON.stringify(myObject, null, 2); console.log(prettyJson);
The output will be:
shell{ "name": "John", "age": 30, "cars": [ "Ford", "BMW", "Fiat" ] }
In this example, we are not using the replacer function (the second parameter of JSON.stringify()), but it can also be used to filter or transform values within the object. If you wish to customize the display of certain properties or exclude specific properties from being printed, you can provide this function.
For example, if you only want to print the second element of the cars array, you can do the following:
javascriptfunction replacer(key, value) { // If the key is 'cars', return only the second element of the array if(key === "cars") { return [value[1]]; } return value; } // Using a custom replacer function and indentation const prettyJson = JSON.stringify(myObject, replacer, 2); console.log(prettyJson);
The output will be:
shell{ "name": "John", "age": 30, "cars": [ "BMW" ] }
This replacer function will only print "BMW" from the cars array. This approach is very useful when dealing with large objects or when you need to filter out sensitive information from the output.