Python format json pretty

How to Pretty Print JSON in Python

Shittu Olumide

Shittu Olumide

How to Pretty Print JSON in Python

JSON (JavaScript Object Notation) is a popular data interchange format that is widely used in web applications, APIs, and databases. It is a lightweight and human-readable format that is easy to parse and generate.

But when dealing with large and complex JSON data, it can be difficult to read and understand the structure of the data. This is where pretty printing comes in. Pretty printing is the process of formatting the JSON data in a way that makes it easier to read and understand.

In this article, we will explore how to pretty print JSON in Python using built-in and third-party libraries. We will also cover best practices used to pretty print JSON, and also talk about it’s use cases.

What Does Pretty Print Mean?

In Python, «pretty print» refers to formatting and presenting data structures such as lists, dictionaries, and tuples in a more readable and organized way.

To pretty print JSON in Python, we can use the built-in json module. This module provides a dumps() function that can serialize Python objects into a JSON formatted string.

By default, this function produces a JSON string without any formatting, but we can use the indent parameter to specify the number of spaces to use for indentation.

Here’s an example of how to pretty print JSON in Python:

import json # Sample JSON data data = < "name": "John", "age": 30, "city": "New York" ># Convert the data to a JSON formatted string with 4 spaces of indentation json_str = json.dumps(data, indent=4) # Print the pretty-printed JSON string print(json_str) 

As you can see, the indent parameter is set to 4 , which produces a JSON string with each level of nesting indented by four spaces. We can adjust this parameter to control the amount of indentation in the output.

Note that the json.dumps() function can also take other optional parameters, such as sort_keys , which can be used to sort the keys in the JSON output. For more information, see the documentation for the json module.

Best Practices for Pretty Print JSON

Use the json module

The json module is a built-in module in Python, which provides methods for working with JSON data. The json.dumps() method is used to serialize Python objects into a JSON formatted string. The json.dumps() method also has an optional indent parameter that can be used to specify the number of spaces to use for indentation.

import json data = < "name": "John", "age": 30, "city": "New York" >json_str = json.dumps(data, indent=4) print(json_str) 

Use the pprint module

The pprint module is a built-in module in Python that provides a way to pretty print Python data structures. It also works with JSON data. The pprint.pprint() method is used to pretty print JSON data.

import json import pprint data = < "name": "John", "age": 30, "city": "New York" >pprint.pprint(data) 

Use third-party libraries

There are many third-party libraries available in Python for pretty printing JSON data, such as simplejson , ujson , and json5 . These libraries provide additional features such as faster serialization and deserialization, support for additional data types, and more flexible formatting options.

Читайте также:  Upload View & Download file in PHP and MySQL | Demo

Here’s an example using simplejson :

import simplejson as json data = < "name": "John", "age": 30, "city": "New York" >json_str = json.dumps(data, indent=4, sort_keys=True) print(json_str) 

Pretty Print JSON in Python Use Cases

  1. Debugging JSON data: When working with JSON data, it can be challenging to read and understand the structure of the data if it is not well-formatted. Pretty printing JSON data in Python can help us to quickly identify any issues with the data and debug our code more efficiently.
  2. Displaying JSON data in user interfaces: If we are building a web application or a mobile app that displays JSON data to the user, pretty printing can enhance the user experience by making the data more readable and presentable.
  3. Sharing JSON data with team members: If we are working on a project with other team members and need to share JSON data with them, pretty printing the data can make it easier for them to understand the data and work with it.
  4. Logging JSON data: If we are logging JSON data in our Python application, pretty printing the data can make it easier to read and analyze the logs.

Conclusion

Pretty printing JSON in Python is an important skill to have for anyone working with JSON data.

In this tutorial, we learned how to use the json module in Python to pretty print JSON as well as the pprint module. With just a few lines of code, we can generate well-formatted JSON output that is easy to read and navigate.

Let’s connect on Twitter and on LinkedIn. You can also subscribe to my YouTube channel.

Источник

Python Pretty Print JSON

Python Pretty Print JSON

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

We can use the Python json module to pretty-print the JSON data. The json module is recommended to work with JSON files. We can use the dumps() method to get the pretty formatted JSON string.

1. Python Pretty Print JSON String

import json json_data = '[,' \ ']' json_object = json.loads(json_data) json_formatted_str = json.dumps(json_object, indent=2) print(json_formatted_str) 
  • First of all, we are using json.loads() to create the json object from the json string.
  • The json.dumps() method takes the json object and returns a JSON formatted string. The indent parameter is used to define the indent level for the formatted string.

2. Python Pretty Print JSON File

Let’s see what happens when we try to print a JSON file data. The file data is saved in a pretty printed format.

Json Pretty Printed File

import json with open('Cars.json', 'r') as json_file: json_object = json.load(json_file) print(json_object) print(json.dumps(json_object)) print(json.dumps(json_object, indent=1)) 

It’s clear from the output that we have to pass the indent value to get the JSON data into a pretty printed format.

Читайте также:  Читалки для java телефона

References

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Python Pretty Print JSON

Here is an illustration of what pretty printing does to JSON objects:

In this guide, you learn why JSON is usually unreadable and how to use pretty printing to fix the problem. You will also see some common examples when pretty-printing.

Before learning how to pretty-print JSON, let’s take a quick look at what JSON really is.

What is JSON?

JSON stands for JavaScript Object Notation. It is a popular text-based data format used broadly to represent structured data.

JSON is commonly used to transmit data between the client and a server because JSON is nothing but structured text, making it a lightweight data format.

Almost every programming language supports JSON, Python being no exception.

The Problem with JSON in Python

When transmitting data over the internet, you want to be as efficient as possible. A really good starting point is to send as little data as possible.

When sending a JSON object over the internet, the JSON payload is sent in an optimized format to save bandwidth.

The problem with the optimized JSON is it is hard to read. To make the JSON readable, you can use what is called pretty printing.

This guide teaches you how to format your JSON objects in a readable fashion by pretty printing them.

Python JSON Pretty Printing

JSON pretty-printing is possible by using the built-in JSON module in Python.

There are three common situations when you might want to use pretty printing when dealing with JSON:

  1. Pretty-print a JSON object to the console.
  2. Write pretty-printed JSON object to a file.
  3. Read + pretty-print a JSON object into the console.

Let’s go through each possibility by showing an example.

How to Pretty-Print a JSON String in Python

To pretty-print a JSON string in Python:

  • Call json.loads() to convert the JSON string to a Python object.
  • Use the json.dumps() method to pretty-print the object

The complete syntax of the json.dumps() method is a pretty lengthy multi-parameter call:

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)

But in this guide and most of the time, all you need to know is this syntax:

  • obj is the JSON object.
  • indent specifies the number of spaces.

If the indent parameter is negative, 0, or an empty string there will be no indentations in the resulting JSON.

By default, the indent is None and the JSON data is represented in a single line.

import json #Initialize JSON data as a JSON string json_data = '[ , \ < "name": "Sofie", "topics": ["Java", "Functional Programming"]>]' #Convert JSON to Python object obj = json.loads(json_data) #Python pretty print JSON json_formatted_str = json.dumps(obj, indent=4) print(json_formatted_str)

As you can see, now the JSON data is nicely formatted. This JSON is really easy to read as opposed to the lengthy one-liner JSON.

How to Write Pretty-Printed JSON String to a File

You can write a pretty printed JSON object to a text file using json.dump() method. The complete syntax of the json.dump() method is a rather verbose multi-parameter function call:

json.dump(obj, file, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None)

But in this guide, you only need to focus on the arguments obj, file, and indent. This simplifies the syntax to:

  • obj is the JSON object to pretty-printed.
  • file is the file to which you want to pretty-print the JSON.
  • indent is the number of indentations in the JSON data in the new lines.
Читайте также:  Css включить перенос строк

Let’s take a look at a simple example of pretty printing to a file:

#Import json module import json #Initialize JSON data as a JSON string json_data = [, ] #Write pretty print JSON data to file with open("example.json", "w") as write_file: json.dump(json_data, write_file, indent=4)

Running this piece of code results in a new file being created with the following contents:

Python pretty print JSON

As you can tell, this file contains nicely formatted JSON data in it. In this form, the file is easy to read, and understanding the JSON structure is clear.

Read + Pretty-Print a JSON File in Python

So far you’ve only worked with JSON objects that you have created directly in your code.

But commonly, you need to be able to read JSON files stored:

Let’s see how to read and pretty-print the JSON data in both situations.

1. Read a JSON File from Your Machine

You can read a JSON object from a file or URL with the json.load() method. Then use the json.dumps() method to pretty-print the JSON.

To demonstrate, let’s read the file you just created in the previous example:

import json with open("example.json", "r") as read_file: obj = json.load(read_file) print(json.dumps(obj, indent=4))

Once again, the JSON data looks great this way as the data is spread across the lines in a structured format rather than a single one-liner.

2. How to Read a JSON File from a URL in Python

You can also read a JSON file from a URL and pretty-print it to the console in Python.

To fetch data behind a URL, use the urllib module. If you don’t have urllib installed on your system, install it by running the following in the command line:

For instance, let’s fetch a list of ToDo items from https://jsonplaceholder.typicode.com/todos. If you open up this site with your browser, you see a bunch of JSON data that represents dummy ToDo items.

JSON example

Our goal is to show a similar-looking pretty-printed ToDo JSON object in the console.

  1. Fetch the contents of a web page with urlopen() function.
  2. Load the JSON data from the website content using json.loads() method.
  3. Pretty-print the JSON object using the json.dumps() method.
from urllib.request import urlopen import json # Step 1. response = urlopen("https://jsonplaceholder.typicode.com/todos") # Step 2. data_json = json.loads(response.read()) # Step 3. pretty_json = json.dumps(data_json, indent=4) print(pretty_json)

As a result of running this piece of code, you should see a pretty printed long list of ToDo items.

JSON pretty-print in Python

Conclusion

Today you learned how to pretty-print JSON data in Python.

To recap, JSON is a commonly used text-based data format that works in Python. To be as efficient as possible, JSON data is compressed when sent over the internet. This compressed format comes at the expense of readability and usually, the JSON is just a lengthy oneliner of nonsense.

To read the JSON data you need to format it in a structured fashion. This is called pretty-printing and is easy in Python with built-in methods. To improve JSON readability, you can pretty-print the JSON object using the json.dumps() method.

See Also

Источник

Оцените статью