Python JSON Pretty Print: What is Pretty-Print in Python?


JSON(JavaScript Object Notation) is a standard format for storing data. It’s a human-readable format that’s easy to parse and is often used with JavaScript.

Pretty print is a feature that allows JSON data to be displayed in a more human-readable format. When should you use pretty print? Let’s take a look.

What is Pretty Print?

Pretty print is a way of displaying JSON data in a more human-readable format. The JSON data is displayed with indents and line breaks so that it’s easier to read. With pretty print, the JSON data is displayed in a more structured way which makes it easier for developers to work with large amounts of JSON data.

When to Use Pretty Print?

There are two main scenarios when you would want to use pretty print.

  • The first scenario is when you’re working with large amounts of data.
  • The second scenario is when you want to share your code with other developers. If you’re working with large amounts of data, pretty print can help you make sense of the data by displaying it in a more structured way. If you’re sharing your code with other developers, they’ll be able to understand your code better if it’s displayed in a more readable format.

Python’s built-in JSON library provides a way for us to work with JSON data in an easy, straightforward manner. But what happens when we have a lot of JSON data that is not so easy to read?

In these cases, we can use the json.dumps() method to format our data in a “pretty” way that is easier for us to read. Let’s take a look at an example.

Consider the following JSON data:

import json json_data = '[{"ID":20,"Name":"John","Role":"CEO"},' \ '{"ID":30,"Name":"Marry","Role":"Editor"}]' json_object = json.loads(json_data) json_Pretty_str = json.dumps(json_object, indent=2) print(json_Pretty_str)
Code language: JSON / JSON with Comments (json)

Output:

[ { "ID": 20, "Name": "John", "Role": "CEO" }, { "ID": 30, "Name": "Marry", "Role": "Editor" } ]
Code language: Python (python)

Conclusion:

Pretty print is a great tool for developers who are working with large amounts of JSON data or who want to share their code with other developers. It helps make the data more readable and easier to work with. In some cases, pretty print can also help make your code more understandable for other developers.

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts