How to pretty print json using javascript?



Java Script Object Notation is one of the many standard formats to store data in different many applications. JavaScript objects can also be stored in a file in this JSON format. In this article, we will cover a few methods to print the JSON objects in a pretty method. Let us see this as an example. We are creating an object in javascript before −

Example (Creating Javascript Object)

var vehicle = { id : 'v01', type : 'bus', length: 6 }

Now let us print this into the console and see whether it shows in a pretty form or not.

Example

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { var vehicle = { id: 'v01', type: 'bus', length: 6 } content += 'The vehicle object: ' + JSON.stringify(vehicle) + "<br>"; } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

It is showing the output straightforwardly and for a simple example, it is easily readable. But for larger nested objects the readability will be degraded. Let us see one bigger JSON object with few nesting.

Example

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { var book = { "b_id": "b_001", "author": { "lastname": "Paul", "firstname": "Alice" }, "editor": { "lastname": "Smith", "firstname": "Bob" }, "title": "A sample book for JSON", "category": ["Javascript", "JSON", "Data Formatting"] } content += 'The book object: ' + JSON.stringify(book) + "<br>"; } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

Now we can see the output is not showing in a readable format. We can make it readable by stringify() function that comes with javascript JSON objects. Let us see the example to check the difference in the output−

Example

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <div id="output"> </div> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { var vehicle = { id: 'v01', type: 'bus', length: 6 } var book = { "b_id": "b_001", "author": { "lastname": "Paul", "firstname": "Alice" }, "editor": { "lastname": "Smith", "firstname": "Bob" }, "title": "A sample book for JSON", "category": ["Javascript", "JSON", "Data Formatting"] } content += 'The vehicle object: ' + JSON.stringify(vehicle) +"<br>"; content += 'The book object: ' + JSON.stringify(book) + "<br>"; } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

This output is less readable than before. So why do we use this to print JSON strings with stringify()? Well, we can improve the printing pattern by adding a few parameters to the stringify() function. The first and essential parameter is the JSON object. The second parameter is replacer. This optional parameter takes a function or an array to transform the result. This item will be called after each item. In our example we are not using this, we are passing null into it. The last parameter is space count, which helps to print JSON problems in a pretty format. For different levels, it will add a given number of white spaces to maintain the indent. Let us see the output of this example−

Example

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <pre id="output"> </pre> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { var vehicle = { id: 'v01', type: 'bus', length: 6 } var book = { "b_id": "b_001", "author": { "lastname": "Paul", "firstname": "Alice" }, "editor": { "lastname": "Smith", "firstname": "Bob" }, "title": "A sample book for JSON", "category": ["Javascript", "JSON", "Data Formatting"] } content += 'The vehicle object: <br>' + JSON.stringify(vehicle, null, 4) + "<br>"; content += 'The book object: <br>' + JSON.stringify(book, null, 4) + "<br>"; } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

Now it is working and displaying the object in a pretty format. We can change the parameters for better and more suitable results. Let us see another example by passing the replacer parameter (second parameter) into the stringify function to replace given values according to the function.

Example

<!DOCTYPE html> <html> <head> <title>HTML Console</title> </head> <body> <h3> Output Console </h3> <p> Output: </p> <pre id="output"> </pre> <div id="opError" style="color : #ff0000"> </div> <script> var content = '' var error = '' var opDiv = document.querySelector('#output') var opErrDiv = document.querySelector('#opError') // actual javascript code try { function makeNameUppercase(key, value) { if (key == "firstname" || key == "lastname") { return value.toUpperCase(); } else { return value; } } var book = { "b_id": "b_001", "author": { "lastname": "Paul", "firstname": "Alice" }, "editor": { "lastname": "Smith", "firstname": "Bob" }, "title": "A sample book for JSON", "category": ["Javascript", "JSON", "Data Formatting"] } content += 'The book object: <br>' + JSON.stringify(book,makeNameUppercase, 4) + "<br>"; } catch (err) { error += err } finally { // display on output console opDiv.innerHTML = content opErrDiv.innerHTML = error } </script> </body> </html>

In this example, we have defined a function that will check if the given key is ‘firstname’ or ‘lastname’, if so then convert the value into uppercase, otherwise simply return the value as it was.

Conclusion

Java Script Object Notation (JSON) format is used in many applications. From Javascript also we can return JSON objects. In this article, we have seen different examples to return JSON objects in pretty format. Without using any 3rd party libraries, we can use stringify() method present in the JSON library. This takes three types of parameters. The first one is the javascript object. The second one is an array or function which is called after each key-value pair is processed. The third parameter is the space count which will print spaces at each indentation level to display the result in a pretty format.


Advertisements