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

How Can I Pretty Print JSON Files in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 04:27:12425browse

How Can I Pretty Print JSON Files in Python?

Formatting JSON Files with Pretty Printing

Often, JSON files can become difficult to read due to their lack of indentation and line breaks. To improve readability, you may want to format your JSON files using a technique known as "pretty printing."

Pretty Printing in Python

Python provides two methods for pretty printing JSON files: json.dump() and json.dumps(). Both methods accept an indent parameter that allows you to specify the number of spaces to indent each level of the JSON hierarchy.

import json

your_json = '["foo", {"bar": ["baz", null, 1.0, 2]}]'

parsed = json.loads(your_json)

print(json.dumps(parsed, indent=4))

Output:

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

Pretty Printing from a File

If you have a JSON file stored in a file called 'filename.txt', you can also pretty print it by first parsing the file using json.load():

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

Once parsed, you can dump the JSON object using json.dumps() with the desired indentation:

print(json.dumps(parsed, indent=4))

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

Statement:
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