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

How Can I Pretty-Print JSON Files in Python?

DDD
DDDOriginal
2024-12-08 19:03:12972browse

How Can I Pretty-Print JSON Files in Python?

Pretty-Printing JSON Files in Python

When analyzing or manipulating JSON data, it can often be helpful to have it formatted in a human-readable way for easier viewing.

Pretty-Printing with JSON

To pretty-print a JSON file in Python, utilize the indent parameter of the json.dump() or json.dumps() functions. Specify the desired number of spaces for indentation in the indent parameter.

For example:

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
        ]
    }
]

In this example, the indent parameter is set to 4, resulting in indented JSON with 4 spaces.

Pretty-Printing JSON Files

To pretty-print a JSON file, you can make use of the json.load() function:

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

This loads the JSON file into the parsed variable, which can then be pretty-printed using the json.dumps() function as shown above.

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