Python In 30 Days - Day 8
Day eight was about using the built-in JSON module within Python. It wasn't too much different from day seven, so I decided to delete the code for writing to a .txt file and write the methods related to JSON dumping and reading from scratch.
The Challenge:
Replace your plain text file methods with JSON versions:
1. Add a method save_to_json(self, filename) that saves a dictionary containing:
- "restaurant": the name
- "order": the current order list
- "total": the current total
- "saved_at": the current date and time as a string
2. Add a method load_from_json(self, filename) that:
- Loads the JSON file
- Restores
self.orderfrom it - Prints the restaurant name, how many items were loaded, and what the saved total was
- Handles
FileNotFoundErrorgracefully
3. Create an instance, add items, save to JSON, then load into a fresh instance and verify the order and total match
4. After loading, print the raw JSON file contents as a string so you can see the structure — use json.dumps() with indent=4 for this
My Code:
import json
from datetime import datetime
class Restaurant:
def __init__(self, name, menu):
self.name = name
self.menu = menu
self.order = []
def add_item(self, item_name):
try:
price = self.menu[item_name]
except TypeError:
print(f"Sorry, {item_name} is not a string.\n")
except KeyError:
print(f"Sorry, {item_name} is not on the menu!\n")
else:
self.order.append(item_name)
print(f"Added {item_name} to order.")
def print_order(self):
print("\nYour Order:")
print(*self.order, sep="\n")
def get_total(self):
if not self.order:
print("\nWarning: Your order is empty.\n")
return 0
total = 0
for i in self.order:
try:
total += self.menu[i]
except KeyError:
print(f"Warning: {i} is not on the menu. Skipping item.")
return total
def __str__(self):
menu_len = len(self.menu)
order_len = len(self.order)
return f"{self.name} | Menu Items: {menu_len} | Current Order: {order_len}"
def save_to_json(self, filename):
now = datetime.now()
data = {
"restaurant": f"{self.name}",
"order": self.order,
"total": self.get_total(),
"saved_at": now.strftime("%Y-%m-%d, %I:%M %p"),
}
with open(f"{filename}", "w") as f:
json.dump(data, f, indent=4)
def load_from_json(self, filename):
try:
with open(f"{filename}", "r") as f:
loaded_data = json.load(f)
total = loaded_data["total"]
self.order = loaded_data["order"]
len_order = len(self.order)
print("\nReloading Order...")
print(
f"\n{self.name} | Items in Order: {len_order} | Your Total: ${total}\n"
)
dump = json.dumps(loaded_data, indent=4)
print(f"Saved order info:\n {dump}")
except FileNotFoundError:
print("Sorry, file not found")
mario = Restaurant(
"Mario's Restaurant",
{"Pizza": 12, "Breadsticks": 8, "Salad": 6, "Tiramisu": 4, "Wine": 18},
)
print("Welcome to Mario's Restaurant\n\nAdd items to order?\n")
mario.add_item("Pizza")
mario.add_item("Tiramisu")
total = mario.get_total()
print(f"\nYour total: ${total}")
mario.save_to_json("data.json")
new_mario = Restaurant(
"Mario's Restaurant",
{"Pizza": 12, "Breadsticks": 8, "Salad": 6, "Tiramisu": 4, "Wine": 18},
)
print("\nOrder lost...")
new_mario.load_from_json("data.json")
Running the Code:
Welcome to Mario's Restaurant
Add items to order?
Added Pizza to order.
Added Tiramisu to order.
Your total: $16
Order lost...
Reloading Order...
Mario's Restaurant | Items in Order: 2 | Your Total: $16
Saved order info:
{
"restaurant": "Mario's Restaurant",
"order": [
"Pizza",
"Tiramisu"
],
"total": 16,
"saved_at": "2026-05-17, 03:04 PM"
}
I tried to make the readout a little more interesting this time, but either way, I was able to meet the challenge and refresh my memory on I/O for JSON.
Day nine is all about external libraries and API's!