How to Format JSON in Python
Feb 02, 20263 min read
Python's standard library comes with a built-in json module that makes it very easy to parse, modify, and pretty-print JSON data. By using the indent parameter, you can format minified JSON into human-readable output.
Example Code
Python
import json
# Your minified JSON string
data_string = '{"name":"John","age":30,"city":"New York","skills":["Python","Machine Learning"]}'
# Parse the JSON string into a Python dictionary
parsed_json = json.loads(data_string)
# Pretty print the JSON with an indent of 4 spaces
formatted_json = json.dumps(parsed_json, indent=4, sort_keys=True)
print(formatted_json)Common Use Cases
- Logging API responses in a readable format
- Saving configuration files (like config.json) so they can be easily edited by users
- Creating CLI tools that need to output formatted JSON
💡 Pro Tips for Python
- Use
sort_keys=Trueto alphabetically sort the keys for easier visual scanning. - For reading from files, use
json.load(file)and for writing formatted output usejson.dump(data, file, indent=4). - If you are using Django or Flask, you can also return formatted JSON directly in HTTP responses.
If you just need to format a JSON file quickly without writing any code, try our free Online JSON Formatter and Validator.