How to Save a VM Snapshot State to a JSON File in Python
Define a dataclass for a VM snapshot and serialize it to a JSON file, then reload it to verify the state.
Python code
35 linesimport json
from dataclasses import dataclass, asdict
from pathlib import Path
@dataclass
class VMSnapshot:
name: str
memory_mb: int
disk_gb: int
state: str = "saved"
def snapshot_to_file(self, path: Path) -> str:
"""Write snapshot state to a JSON file and return the filename."""
path.write_text(
json.dumps(asdict(self), indent=2)
)
return path.name
if __name__ == "__main__":
snapshot = VMSnapshot(
name="web-server-01",
memory_mb=8192,
disk_gb=200,
state="saved"
)
filename = snapshot.snapshot_to_file(Path("vm_snapshot.json"))
print(f"Snapshot saved to: {filename}")
# Read back to verify
with Path("vm_snapshot.json") as f:
data = json.loads(f.read_text())
print(f"Verified state: {data['state']} @ {data['memory_mb']} MB")
Output
Snapshot saved to: vm_snapshot.json
Verified state: saved @ 8192 MB
How it works
The @dataclass decorator automatically generates an __init__, __repr__ and other methods, reducing boilerplate. asdict() converts the dataclass instance into a plain dictionary, which json.dumps() can serialize with indentation for readability. Writing the JSON to disk with Path.write_text() makes the snapshot durable and easy to inspect. Reloading with json.loads(Path.read_text()) confirms the data round-trips correctly. This pattern is simple, uses only the standard library, and is ideal for lightweight automation scripts.
Common mistakes
- Forgetting that `Path` objects do not have a context manager — use `with open(path)` or call `read_text()` directly.
- Using `json.dump` on a dataclass directly without converting to a dict first — it will raise a TypeError.
- Not setting `indent=2` makes the output a single long line, harder to debug.
- Assuming the file path exists — always ensure the parent directory is present or use `parents=True` with `mkdir()`.
Variations
- Use `Path.write_text(json.dumps(asdict(snapshot)))` without indentation for smaller files.
- Add `default=str` to `json.dumps` if your dataclass has non-serializable fields like datetime objects.
Real-world use cases
- Saving VM configuration snapshots before automated provisioning or rollback in infrastructure scripts.
- Persisting test environment state in CI pipelines for debugging and reproducibility.
- Storing application state in a file-based format for simple backup and restore utilities.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.