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

How Can I Pretty Print JSON Data in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-31 04:49:08798browse

How Can I Pretty Print JSON Data in Python?

Pretty Printing JSON in Python

Pretty printing a JSON file enhances its readability by indenting and formatting its content for human readers. In Python, this can be achieved using the json.dump() or json.dumps() functions.

Using json.dump() and json.loads()

To pretty print a string containing JSON data:

import json

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

# Parse the JSON string
parsed = json.loads(your_json)

# Pretty print the JSON object with 4 spaces of indentation
print(json.dumps(parsed, indent=4))

Using json.load() and json.dumps() with a File:

# Open a file containing JSON data
with open('filename.txt', 'r') as handle:
    # Parse the JSON file
    parsed = json.load(handle)

# Pretty print the JSON object with 2 spaces of indentation
print(json.dumps(parsed, indent=2))

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!

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