Форматированный вывод json python

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.

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.

References

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

Источник

Python PrettyPrint JSON Data

PrettyPrint is useful to display JSON in an easy-to-read (for human readers) format. When we say PrettyPrinting JSON in Python, we consider primarily for indentation, key-value separators, and whitespace.

Scenarios where we need JSON PrettyPrinting In Python:

  • Write PrettyPrinted JSON formatted data into a file
  • Prettyprint JSON file: Let’s say you have a JSON file that is huge and not correctly indented, and you want to prettyprint it
  • Prettyprint JSON formatted string

Further Reading:

Python JSON PrettyPring explained

Write Indented and Pretty-printed JSON data into a file

In real-world cases, we deal with extensive JSON data. When we write JSON data into a file, we must make sure that the JSON data is readable and well organized, so whosever consuming it have a better understanding of the structure of JSON.

Using the json.dump() method of Python json module, we can write prettyprinted JSON into the file. The json.dump() method provides the following parameters to pretty-print JSON data.

The indent parameter specifies the spaces that are used at the beginning of a line. We can use the indent parameter of json.dump() to specify the indentation value. By default, when you write JSON data into a file, Python doesn’t use indentations and writes all data on a single line, which is not readable.

The separator parameter: You can specify any separator between JSON key and value. The default separator is (‘, ‘, ‘: ‘) . For example, if you specify separators such as (‘, ‘, ‘ : ‘) , JSON will look like this.

The sort_keys parameter to sort JSON keys alphabetically.

import json print("Writing Indented and Pretty-printed JSON formatted data into a file") student = < "id": 1, "name": "Jessa Duggar", "class": 9, "attendance": 75, "subjects": ["English", "Geometry"], "email": "jessa@pynative.com" >with open("studentWithoutPrettyPrint.json", "w") as write_file: json.dump(student, write_file) print("Done writing JSON data into file without Pretty Printing it") with open("studentWithPrettyPrint1.json", "w") as write_file: json.dump(student, write_file, indent=4) print("Done writing PrettyPrinted JSON data into file with indent=4") with open("studentWithPrettyPrint2.json", "w") as write_file: json.dump(student, write_file, indent=0) print("Done writing PrettyPrinted JSON data into file with indent=0") with open("studentWithPrettyPrint3.json", "w") as write_file: json.dump(student, write_file, indent=4, sort_keys=True) print("Done writing Sorted and PrettyPrinted JSON data into file")
Writing Indented and Pretty-printed JSON formatted data into a file Done writing JSON data into file without Pretty Printing it Done writing PrettyPrinted JSON data into file with indent=4 Done writing PrettyPrinted JSON data into file with indent=0 Done writing Sorted and PrettyPrinted JSON data into file

JSON file without Pretty Printing it

Pretty-Printed JSON data into a file with indent=0

Источник

Читайте также:  Php get streaming data
Оцените статью