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