Json.tool / Pretty Print Json From File
Pretty Print Json From File
Pretty-prints JSON content from a file using Python's json.tool module.
python -m json.tool <path/to/file.json> python -m json.tool <path/to/file.json> #!/bin/bash
# Pretty Print Json From File
python -m json.tool {{path/to/file.json}} import subprocess
# Pretty Print Json From File
# Make sure to replace <placeholders> with actual values
def run_command():
cmd = [
"json.tool",
"-m",
"json.tool",
"<path/to/file.json>"
]
try:
print(f"Executing: {' '.join(cmd)}")
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError as e:
print(f"Error: {e}")
except FileNotFoundError:
print("Error: json.tool not found. Please install it first.")
if __name__ == "__main__":
run_command() When To Use
When needing to inspect or validate JSON file structure during development or debugging.
Pro Tip
Combine with --sort-keys to output JSON entries in alphabetical order for easy comparison.
Anatomy of Output
Understanding the result
{ Start of JSON Object Indicates the beginning of a JSON structure.
"key": "value", Key-Value Pair Standard key-value structure found within JSON.
} End of JSON Object Indicates the conclusion of the JSON structure.
Troubleshooting
Common pitfalls
FileNotFoundError: [Errno 2] No such file or directory: 'path/to/file.json'
Solution: Check that the specified JSON file path is correct.
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Solution: Verify that the file contains valid JSON formatted content.
PermissionError: [Errno 13] Permission denied: 'path/to/file.json'
Solution: Ensure that you have permission to read the specified JSON file.
Command Breakdown
What each part is doing
-
python - Base Command
- The executable that performs this operation. Here it runs Json.tool before the shell applies any redirect operators.
-
<path/to/file.json> - Input Files
- The file path or paths supplied to this command.
-
-m - Command Option
- Tool-specific option used by this command invocation.
Alternative Approaches
Comparable commands in other tools
Alternative programming tools for the same job.