Home >Backend Development >Python Tutorial >How Can I Pretty-Print JSON Data in Python?
JSON Pretty Printing in Python
JSON, or JavaScript Object Notation, is a lightweight data-interchange format often used to transmit data between servers and clients. However, JSON strings can become difficult to read and debug when they lack proper indentation and formatting.
How to Pretty-Print a JSON File in Python
To pretty-print a JSON file in Python, you can use the indent parameter of either json.dump() or json.dumps(). By specifying how many spaces to indent by, you can significantly enhance the readability of your JSON strings.
Here's an example of pretty-printing a JSON string using json.dumps():
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, we've specified indent=4, resulting in JSON formatted with four spaces of indentation. You can adjust this number to suit your preferences.
To process a JSON file, you can use json.load():
with open('filename.txt', 'r') as handle: parsed = json.load(handle)
By following these methods, you can easily beautify JSON strings and files in Python, making them easier to read and work with.
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!