Serialization of Reports into JSON or Text Files
๐ท๏ธ Final Capstone Engineer Script project / Project: System Health Reporter
๐งญ Context Introduction
After collecting system health dataโCPU usage, memory stats, disk space, and running servicesโthe next logical step is to save that data so it can be reviewed later, shared with teammates, or fed into monitoring dashboards. This process is called serialization: converting in-memory Python objects (like dictionaries and lists) into a storable format. The two most common formats for engineers are JSON (JavaScript Object Notation) and plain text files. JSON is structured and machine-readable, while text files are simple and human-friendly. This guide walks through both approaches so you can choose the right one for your system health reports.
โ๏ธ Why Serialize Reports?
- Persistence โ Data survives after the script finishes running.
- Sharing โ Reports can be emailed, uploaded, or stored in a shared directory.
- Automation โ Other tools (like log aggregators or dashboards) can ingest JSON files.
- Audit Trail โ Historical snapshots let you compare system health over time.
๐ JSON Serialization โ Structured & Machine-Friendly
JSON is the go-to format when you need to parse the report programmatically. Python's built-in json module handles the conversion.
Key steps:
- Import the json module at the top of your script.
- Build a Python dictionary containing all your system health metrics (CPU, memory, disk, services).
- Use json.dumps() to convert the dictionary into a JSON string.
- Write that string to a file using Python's open() function with 'w' mode.
- For pretty printing (readable indentation), pass the indent=4 argument to json.dumps().
Example flow (no code blocks):
- Create a dictionary like report = {"timestamp": "2025-04-10 14:30", "cpu_percent": 45.2, "memory_used_mb": 2048}
- Call json.dumps(report, indent=4) to get a formatted JSON string.
- Open a file named system_report.json with open("system_report.json", "w") as f:
- Write the string with f.write(json_string) .
Result: A file that looks like a clean, indented JSON objectโperfect for loading into other scripts or tools.
๐ ๏ธ Text File Serialization โ Simple & Human-Readable
Sometimes you just want a quick, readable log. Text files are ideal for that. No special modules are neededโjust Python's built-in file handling.
Key steps:
- Build a string that contains your report in plain English (or any format you prefer).
- Use open() with 'w' mode to create or overwrite a text file.
- Write each line with f.write() or use f.writelines() for a list of strings.
- Add timestamps and section headers to make the text file easy to scan.
Example flow (no code blocks):
- Construct a multi-line string: report_text = "System Health Report\nDate: 2025-04-10\nCPU: 45.2%\nMemory: 2048 MB used\n"
- Open system_report.txt with open("system_report.txt", "w") as f:
- Write the entire string with f.write(report_text) .
Result: A plain text file that can be opened in any editor or printed directly to the terminal with cat or type.
๐ต๏ธ JSON vs Text โ When to Use Which
| Aspect | JSON | Text File |
|---|---|---|
| Readability for humans | Moderate (with indentation) | High (plain language) |
| Readability for machines | Excellent (parsed easily) | Low (needs custom parsing) |
| Size on disk | Slightly larger (brackets, quotes) | Smaller (no extra syntax) |
| Ease of automation | High (load with json.load()) | Low (string parsing required) |
| Best use case | Feeding into dashboards, APIs, or scripts | Quick logs, email reports, manual review |
๐ File Naming & Organization Tips
- Use timestamps in filenames to avoid overwriting: system_report_2025-04-10.json
- Store reports in a dedicated directory like ./reports/ for clean project structure.
- For repeated runs, append to a single log file using 'a' (append) mode instead of 'w' (write).
- Consider compressing old JSON reports with gzip if disk space is a concern.
๐งช Common Pitfalls to Avoid
- Forgetting to close the file โ Always use the with statement (context manager) so files close automatically.
- Trying to serialize non-serializable objects โ JSON only supports dicts, lists, strings, numbers, booleans, and None. Convert custom objects (like datetime) to strings first.
- Overwriting previous reports โ Use unique filenames (timestamped) or append mode to preserve history.
- Writing binary data to text mode โ Use 'wb' for binary files (like compressed JSON) and 'w' for text.
๐ Next Steps for Your Project
- Combine both formats: save a JSON file for automation and a text file for quick viewing.
- Add error handling with try/except blocks around file operations to handle permission errors or missing directories.
- Extend your report to include network stats, disk I/O, or running process counts.
- Schedule your script with cron (Linux) or Task Scheduler (Windows) to generate reports automatically.
โ Summary
Serialization turns your live system health data into permanent, shareable reports. JSON gives you structure and machine readabilityโperfect for feeding into other tools. Text files give you simplicity and immediate human readabilityโgreat for quick checks and logs. By mastering both, you can build a flexible reporting system that serves both automated pipelines and manual reviews. Start with one format, then add the other as your project grows.
This topic shows how to save system health report data into JSON and text files so engineers can store and share results.
๐ Example 1: Writing a simple string to a text file
This example writes a single line of text into a new file.
report = "System health: OK"
with open("report.txt", "w") as file:
file.write(report)
๐ค Output: report.txt file created with content "System health: OK"
๐ Example 2: Writing multiple lines to a text file
This example writes a multi-line report using a list of strings.
lines = ["CPU: 45%", "Memory: 2.1 GB used", "Disk: 120 GB free"]
with open("report.txt", "w") as file:
for line in lines:
file.write(line + "\n")
๐ค Output: report.txt file created with three lines of health data
๐ Example 3: Converting a dictionary to JSON and saving it
This example takes a Python dictionary and writes it as a JSON file.
import json
report_data = {
"cpu_usage": 45,
"memory_used_gb": 2.1,
"disk_free_gb": 120
}
with open("report.json", "w") as file:
json.dump(report_data, file)
๐ค Output: report.json file created with JSON-formatted dictionary
๐ Example 4: Reading a JSON file back into Python
This example loads the JSON file created in Example 3 and prints the data.
import json
with open("report.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data)
๐ค Output: {'cpu_usage': 45, 'memory_used_gb': 2.1, 'disk_free_gb': 120}
๐ Example 5: Writing a list of reports to JSON with pretty printing
This example saves multiple system health snapshots with readable indentation.
import json
reports = [
{"timestamp": "2024-01-15 10:00", "cpu": 45, "memory": 2.1},
{"timestamp": "2024-01-15 11:00", "cpu": 62, "memory": 3.4},
{"timestamp": "2024-01-15 12:00", "cpu": 38, "memory": 1.8}
]
with open("reports.json", "w") as file:
json.dump(reports, file, indent=4)
๐ค Output: reports.json file created with three report entries, each indented for readability
Comparison Table: Text Files vs JSON Files
| Feature | Text File (.txt) | JSON File (.json) |
|---|---|---|
| Data structure | Plain strings | Dictionaries, lists, numbers |
| Readable by humans | Yes, simple | Yes, structured |
| Easy to parse in Python | Manual splitting needed | Built-in json module |
| Supports nested data | No | Yes |
| Best for | Quick notes, logs | Complex report data |
๐งญ Context Introduction
After collecting system health dataโCPU usage, memory stats, disk space, and running servicesโthe next logical step is to save that data so it can be reviewed later, shared with teammates, or fed into monitoring dashboards. This process is called serialization: converting in-memory Python objects (like dictionaries and lists) into a storable format. The two most common formats for engineers are JSON (JavaScript Object Notation) and plain text files. JSON is structured and machine-readable, while text files are simple and human-friendly. This guide walks through both approaches so you can choose the right one for your system health reports.
โ๏ธ Why Serialize Reports?
- Persistence โ Data survives after the script finishes running.
- Sharing โ Reports can be emailed, uploaded, or stored in a shared directory.
- Automation โ Other tools (like log aggregators or dashboards) can ingest JSON files.
- Audit Trail โ Historical snapshots let you compare system health over time.
๐ JSON Serialization โ Structured & Machine-Friendly
JSON is the go-to format when you need to parse the report programmatically. Python's built-in json module handles the conversion.
Key steps:
- Import the json module at the top of your script.
- Build a Python dictionary containing all your system health metrics (CPU, memory, disk, services).
- Use json.dumps() to convert the dictionary into a JSON string.
- Write that string to a file using Python's open() function with 'w' mode.
- For pretty printing (readable indentation), pass the indent=4 argument to json.dumps().
Example flow (no code blocks):
- Create a dictionary like report = {"timestamp": "2025-04-10 14:30", "cpu_percent": 45.2, "memory_used_mb": 2048}
- Call json.dumps(report, indent=4) to get a formatted JSON string.
- Open a file named system_report.json with open("system_report.json", "w") as f:
- Write the string with f.write(json_string) .
Result: A file that looks like a clean, indented JSON objectโperfect for loading into other scripts or tools.
๐ ๏ธ Text File Serialization โ Simple & Human-Readable
Sometimes you just want a quick, readable log. Text files are ideal for that. No special modules are neededโjust Python's built-in file handling.
Key steps:
- Build a string that contains your report in plain English (or any format you prefer).
- Use open() with 'w' mode to create or overwrite a text file.
- Write each line with f.write() or use f.writelines() for a list of strings.
- Add timestamps and section headers to make the text file easy to scan.
Example flow (no code blocks):
- Construct a multi-line string: report_text = "System Health Report\nDate: 2025-04-10\nCPU: 45.2%\nMemory: 2048 MB used\n"
- Open system_report.txt with open("system_report.txt", "w") as f:
- Write the entire string with f.write(report_text) .
Result: A plain text file that can be opened in any editor or printed directly to the terminal with cat or type.
๐ต๏ธ JSON vs Text โ When to Use Which
| Aspect | JSON | Text File |
|---|---|---|
| Readability for humans | Moderate (with indentation) | High (plain language) |
| Readability for machines | Excellent (parsed easily) | Low (needs custom parsing) |
| Size on disk | Slightly larger (brackets, quotes) | Smaller (no extra syntax) |
| Ease of automation | High (load with json.load()) | Low (string parsing required) |
| Best use case | Feeding into dashboards, APIs, or scripts | Quick logs, email reports, manual review |
๐ File Naming & Organization Tips
- Use timestamps in filenames to avoid overwriting: system_report_2025-04-10.json
- Store reports in a dedicated directory like ./reports/ for clean project structure.
- For repeated runs, append to a single log file using 'a' (append) mode instead of 'w' (write).
- Consider compressing old JSON reports with gzip if disk space is a concern.
๐งช Common Pitfalls to Avoid
- Forgetting to close the file โ Always use the with statement (context manager) so files close automatically.
- Trying to serialize non-serializable objects โ JSON only supports dicts, lists, strings, numbers, booleans, and None. Convert custom objects (like datetime) to strings first.
- Overwriting previous reports โ Use unique filenames (timestamped) or append mode to preserve history.
- Writing binary data to text mode โ Use 'wb' for binary files (like compressed JSON) and 'w' for text.
๐ Next Steps for Your Project
- Combine both formats: save a JSON file for automation and a text file for quick viewing.
- Add error handling with try/except blocks around file operations to handle permission errors or missing directories.
- Extend your report to include network stats, disk I/O, or running process counts.
- Schedule your script with cron (Linux) or Task Scheduler (Windows) to generate reports automatically.
โ Summary
Serialization turns your live system health data into permanent, shareable reports. JSON gives you structure and machine readabilityโperfect for feeding into other tools. Text files give you simplicity and immediate human readabilityโgreat for quick checks and logs. By mastering both, you can build a flexible reporting system that serves both automated pipelines and manual reviews. Start with one format, then add the other as your project grows.
Interactive Views
You are currently in ๐ All-in-One mode. Use the tabs at the top to switch to ๐ Theory Only or ๐ป Code Only views.
This topic shows how to save system health report data into JSON and text files so engineers can store and share results.
๐ Example 1: Writing a simple string to a text file
This example writes a single line of text into a new file.
report = "System health: OK"
with open("report.txt", "w") as file:
file.write(report)
๐ค Output: report.txt file created with content "System health: OK"
๐ Example 2: Writing multiple lines to a text file
This example writes a multi-line report using a list of strings.
lines = ["CPU: 45%", "Memory: 2.1 GB used", "Disk: 120 GB free"]
with open("report.txt", "w") as file:
for line in lines:
file.write(line + "\n")
๐ค Output: report.txt file created with three lines of health data
๐ Example 3: Converting a dictionary to JSON and saving it
This example takes a Python dictionary and writes it as a JSON file.
import json
report_data = {
"cpu_usage": 45,
"memory_used_gb": 2.1,
"disk_free_gb": 120
}
with open("report.json", "w") as file:
json.dump(report_data, file)
๐ค Output: report.json file created with JSON-formatted dictionary
๐ Example 4: Reading a JSON file back into Python
This example loads the JSON file created in Example 3 and prints the data.
import json
with open("report.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data)
๐ค Output: {'cpu_usage': 45, 'memory_used_gb': 2.1, 'disk_free_gb': 120}
๐ Example 5: Writing a list of reports to JSON with pretty printing
This example saves multiple system health snapshots with readable indentation.
import json
reports = [
{"timestamp": "2024-01-15 10:00", "cpu": 45, "memory": 2.1},
{"timestamp": "2024-01-15 11:00", "cpu": 62, "memory": 3.4},
{"timestamp": "2024-01-15 12:00", "cpu": 38, "memory": 1.8}
]
with open("reports.json", "w") as file:
json.dump(reports, file, indent=4)
๐ค Output: reports.json file created with three report entries, each indented for readability
Comparison Table: Text Files vs JSON Files
| Feature | Text File (.txt) | JSON File (.json) |
|---|---|---|
| Data structure | Plain strings | Dictionaries, lists, numbers |
| Readable by humans | Yes, simple | Yes, structured |
| Easy to parse in Python | Manual splitting needed | Built-in json module |
| Supports nested data | No | Yes |
| Best for | Quick notes, logs | Complex report data |