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
Release: 2024-12-09 04:27:12
Original
426 people have browsed it

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))
Copy after login

Output:

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

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)
Copy after login

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

print(json.dumps(parsed, indent=4))
Copy after login

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!

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