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
Release: 2024-12-31 04:49:08
Original
757 people have browsed it

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

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

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