code
code
class Order:
def __init__(self, json_data):
self.data = json.loads(json_data)
self.order_id = self.data.get("order_id")
self.customer = Customer(self.data.get("customer"))
self.items = [Item(item) for item in self.data.get("items", [])]
class Customer:
def __init__(self, customer_data):
self.name = customer_data.get("name")
self.email = customer_data.get("email")
class Item:
def __init__(self, item_data):
self.product_id = item_data.get("product_id")
self.quantity = item_data.get("quantity")
self.price = item_data.get("price")
# Example usage
json_string = """{
"order_id": 12345,
"customer": {"name": "John Doe", "email": "[email protected]"},
"items": [
{"product_id": 1, "quantity": 2, "price": 19.99},
{"product_id": 2, "quantity": 1, "price": 9.99}
]
}"""
order = Order(json_string)
print("Order ID:", order.order_id)
print("Customer Name:", order.customer.name)
print("Customer Email:", order.customer.email)
for item in order.items:
print(f"Product ID: {item.product_id}, Quantity: {item.quantity}, Price: ${item.price:.2f}")