October 2, 2020
2 mins read

Pretty Printing JSON to Make it More Readable

JSON is a popular way to encode data objects in a format that’s easy for both humans and machines to read. However, relying on the standard console window isn’t always the most user-friendly way of seeing this formatted representation. In this post, we’ll discuss how you can make your JSON string far more readable by using javascript.

What is JSON and how it’s structured

JSON stands for JavaScript Object Notation and is a lightweight data-interchange format. JSON is typically used for passing information between different parts of an application, especially Ajax calls and server-side processes.

JSON is structured as a collection of name/value pairs, usually wrapped in curly braces or square brackets and separated by commas. The name is always on the left hand side and the value on the right hand side. Values can either be strings or numbers

Why you need to pretty print JSON strings

JSON is a standardized format for transferring data that is often used when building an API. When it’s not pretty printed, it will look like a bunch of code with no spaces or indentations. You might be able to see what the JSON data looks like by decoding it but decoding JSON strings can be tedious and time-consuming. Pretty printing will make your JSON more readable so you can identify where the data starts and ends.

How to pretty print JSON strings

Using vanilla javascript we can pretty-print JSON strings. The following example converts a JSON string into a more readable format:

function main(input) {
    input.text = JSON.stringify(jsonObj, null, 4);
}

Let dissect the above code snippet. The null parameter passed to the second argument is the replacer and the number argument 4 is the amount of spaces to use for each indention level.

Conclusion

If you need to work with JSON on a regular basis then you might want to consider using Polypad. This tool will take your JSON and create a comma-separated values output which is much more readable.