How to beautify and pretty print formatted JSON in Python

JSON in few words

JSON (i.e. JavaScript Object Notation) syntax is based on a subset of the JavaScript programming language. It is a simple, easy to read, write, parse and transform data exchange format. JSON is extremely popular in building REST based web services. Recall that not only JSON but also other formats such as XML can be used to exchange data. This article is not the right venue to debate which is better.

So et us get started…

Why do we need to beautify JSON

Beatification of source code makes it easy to read which is handy when debugging and testing. Of course, production code is encouraged to be minified specially in web applications as it reduces download time. Before we jump to the main topic, let us briefly describe what JSON is…

Making sense of JSON

An easy way to make sense of JSON data format is to think of it like a database table. Data in a database table is organized into rows (records) and columns (fields). Similarly, JSON can be used to serialize data in the form of programming language objects (primitive data types, arrays and dictionaries) to be stored on disk.

Let us take an example…

In the above example, here are few observations…

  • name is a key and John is the corresponding value, or a column value in a database table
  • [] is an array, in this example, we have two records or two rows in a database
  • {} is used to represent dictionaries to map keys to values

Online code beautification tools

If you want to quickly beautify the example JSON data above without writing code, you can do so online easily. There are few tools that just do that. For example…

  • Go to jsoneditoronline.org
  • Paste the JSON file in the left side of the screen
  • Click the right arrow and see how the JSON file will look like

We are going to do something similar. The above JSON file is typically transmitted as one long ugly string.

JSON beatification

Just take a look at the following Python code snippet. The code is explained in details using comments

How to format a JSON file

If JSON data is stored in a disk file, we can easily apply the same technique. The only difference is that we just need to add file IO code. Here is an example code snippet that demonstrate how to read/write a JSON string from/to file…

JSON formatting from the command line

We can format and validate a JSON file on the fly using the terminal. Assume that the JSON data file mentioned earlier is saved to a file called input.json. We can do so by typing the following command

Please note the following…

  • m option allows Python to load a module from the command line
  • json.tool validates and pretty print the JSON file

If you execute the command above you should get the following output…


Thanks for reading. Please use the comments below for questions.

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *