Pretty Print JSON Python


“JSON or JavaScript Object Notation is a lightweight data exchange format that is widely adopted by modern applications. Whether you are working in NoSQL databases or fetching API data, you will encounter JSON.

It is a heavily adopted language due to its simplicity but strict schema. This helps to reduce errors while still retaining human readability.

Luckily, Python has a built-in package called json that allows us to interact and process JSON data.

For this tutorial, we will cover how you can pretty-print JSON data using Python’s json module.”

Let’s get started.

Python json.dumps() Function

To pretty print JSON data in Python, we use the dumps method from the json module. The function syntax is as shown:

1

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

The function parameters are as discussed below:

  1. obj – refers to the JSON object you wish to print.
  2. skipkeys – if set to true, the function will skip keys that are not of str, int, float, bool, or None type. This value is set to false by default.
  3. ensure_ascii – if set to true, the function will return an output with non-ascii characters escaped. This value is true by default.
  4. check_circular – skips the circular reference check for container types if true. Otherwise, return OverFlowError.
  5. allow_nan – out of range floats are substituted for NaN, Infinity, or -Inifinity if set to true.
  6. indent – specifies the indent level for the pretty-print format. If the indent level is 0 or negative, the function will only print new lines. For a more compact representation of the data, ensure to specify a positive integer of above 1.
  7. separators – specify the item and key separate characters.
  8. sort_keys – if true, the function sorts the output dictionary by its keys.

Let us explore how we can use this function to pretty-print JSON data.

Example 1

The example below shows how to use the json.dumps() function to pretty-print a JSON object.

1
2
3
4
5
6
7
8
9
10
11

from json import dumps, loads

 

data = ‘{«id»:1,»first_name»:»Jada»,»last_name»:»Deport»,»email»:»[email protected]«,»gender»:»Female»,»ip_address»:»68.40.159.153″}’

 

json_object = loads(data)

print(dumps(json_object, indent=3))

We start by importing the required functions. In our case, we need the dumps() function to pretty-print the json object and the loads to deserialize the json into a Python object.

Next, we create a variable holding the raw JSON data. We convert it into a Python object using the loads’ function and finally, pretty print it with the dumps() function.

The resulting output is as shown:

1
2
3
4
5
6
7
8
9

$ python pretty_print.py
{
   «id»: 1,
   «first_name»: «Jada»,
   «last_name»: «Deport»,
   «email»: «[email protected]«,
   «gender»: «Female»,
   «ip_address»: «68.40.159.153»
}

The code below shows the same JSO output level with an indent level of 1.

1
2
3
4
5
6
7
8
9
10
11

from json import dumps, loads

 

data = ‘{«id»:1,»first_name»:»Jada»,»last_name»:»Deport»,»email»:»[email protected]«,»gender»:»Female»,»ip_address»:»68.40.159.153″}’

 

json_object = loads(data)

print(dumps(json_object, indent=1))

The resulting output:

Note that the indent level of 3 adds more whitespace characters when printing the JSON.

Example 2 – Sorting Keys

We can also sort the keys of the output dictionary by setting the sort_keys parameter to True.

Consider the example below:

1
2
3
4
5
6
7
8
9
10
11

from json import dumps, loads

 

data = ‘{«id»:1,»first_name»:»Jada»,»last_name»:»Deport»,»email»:»[email protected]«,»gender»:»Female»,»ip_address»:»68.40.159.153″}’

 

json_object = loads(data)

print(dumps(json_object, indent=1, sort_keys=True))

The code should sort the keys of the output dictionary in ascending order as shown:

Note how each key in the resulting dictionary is sorted in alphabetical order.

Example 3 – Pretty Print JSON From File

Using Python’s open function, we can load data from a JSON file and pretty print it. Suppose we have a JSON file as shown:

We can load the file and use the json.dumps() method as shown in the example code below:

1
2
3
4
5
6
7

from json import dumps, load

with open(‘net_info.json’, ‘r’) as f:

    json_data = load(f)

print(dumps(json_data, indent=1))

In the example above, we use the load function to load the JSON data from the file into a JSON object.

We then use the dumps function to pretty print with an indent level of 1. The resulting output is as shown:

The output gives us a well-formatted list of Python dictionaries representing the JSON data.

Conclusion

In this tutorial, we learned how to use the JSON dumps function to pretty-print JSON data in Python. We also learned how to sort JSON data by its keys using the sort_keys parameter.

Thanks for reading!!



Source link