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!