Home > Backend Development > Python Tutorial > How Can I Pretty-Print JSON Data in Python?

How Can I Pretty-Print JSON Data in Python?

Mary-Kate Olsen
Release: 2024-12-09 13:28:12
Original
596 people have browsed it

How Can I Pretty-Print JSON Data in Python?

JSON Pretty Printing in Python

JSON, or JavaScript Object Notation, is a lightweight data-interchange format often used to transmit data between servers and clients. However, JSON strings can become difficult to read and debug when they lack proper indentation and formatting.

How to Pretty-Print a JSON File in Python

To pretty-print a JSON file in Python, you can use the indent parameter of either json.dump() or json.dumps(). By specifying how many spaces to indent by, you can significantly enhance the readability of your JSON strings.

Here's an example of pretty-printing a JSON string using json.dumps():

import json

your_json = '["foo", {"bar": ["baz", null, 1.0, 2]}]'
parsed = json.loads(your_json)
print(json.dumps(parsed, indent=4))
Copy after login

Output:

[
    "foo",
    {
        "bar": [
            "baz",
            null,
            1.0,
            2
        ]
    }
]
Copy after login

In this example, we've specified indent=4, resulting in JSON formatted with four spaces of indentation. You can adjust this number to suit your preferences.

To process a JSON file, you can use json.load():

with open('filename.txt', 'r') as handle:
    parsed = json.load(handle)
Copy after login

By following these methods, you can easily beautify JSON strings and files in Python, making them easier to read and work with.

The above is the detailed content of How Can I Pretty-Print JSON Data in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template