Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Inventory Management with JSON in Python
Inventory management is essential for any business that handles products or stock. It involves tracking the flow of goods to ensure adequate supply while avoiding overstocking or stockouts. This tutorial demonstrates how to create an inventory management system using JSON for data storage in Python.
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data interchange format that's easy for humans to read and write. It uses key-value pairs similar to Python dictionaries and is widely used for data exchange between applications.
JSON Syntax
{
"apple": {"price": 10, "quantity": 50},
"banana": {"price": 5, "quantity": 30},
"orange": {"price": 8, "quantity": 25}
}
JSON consists of key-value pairs enclosed in curly braces. Keys are always strings, and values can be strings, numbers, booleans, arrays, or nested objects.
Basic JSON Operations in Python
Python's built-in json module provides functions to work with JSON data ?
import json
# Sample inventory data
inventory_data = {
"apple": {"price": 10, "quantity": 50},
"banana": {"price": 5, "quantity": 30}
}
# Convert Python dict to JSON string
json_string = json.dumps(inventory_data, indent=2)
print("JSON String:")
print(json_string)
# Convert JSON string back to Python dict
parsed_data = json.loads(json_string)
print("\nParsed Data:")
print(parsed_data)
JSON String:
{
"apple": {
"price": 10,
"quantity": 50
},
"banana": {
"price": 5,
"quantity": 30
}
}
Parsed Data:
{'apple': {'price': 10, 'quantity': 50}, 'banana': {'price': 5, 'quantity': 30}}
Method 1: Simple Dictionary-Based Inventory
This approach uses Python's json module with a dictionary to manage inventory data ?
import json
# Initialize inventory
inventory = {
"apple": {"price": 10, "quantity": 50},
"banana": {"price": 5, "quantity": 30}
}
def add_item(name, price, quantity):
inventory[name] = {"price": price, "quantity": quantity}
print(f"Added {name} to inventory")
def remove_item(name):
if name in inventory:
del inventory[name]
print(f"Removed {name} from inventory")
else:
print(f"Item {name} not found")
def display_inventory():
print(f"{'Item':<15} {'Price':<10} {'Quantity':<10}")
print("-" * 35)
for item, data in inventory.items():
print(f"{item:<15} {data['price']:<10} {data['quantity']:<10}")
def save_to_file(filename):
with open(filename, 'w') as f:
json.dump(inventory, f, indent=2)
print(f"Inventory saved to {filename}")
# Test the functions
add_item("orange", 8, 25)
display_inventory()
print()
remove_item("banana")
display_inventory()
Added orange to inventory Item Price Quantity ----------------------------------- apple 10 50 banana 5 30 orange 8 25 Removed banana from inventory Item Price Quantity ----------------------------------- apple 10 50 orange 8 25
Method 2: Object-Oriented Inventory Class
This approach uses a custom class to encapsulate inventory operations and data management ?
import json
class InventoryManager:
def __init__(self):
self.inventory = {}
def add_item(self, name, price, quantity):
self.inventory[name] = {"price": price, "quantity": quantity}
return f"Added {name} to inventory"
def remove_item(self, name):
if name in self.inventory:
del self.inventory[name]
return f"Removed {name} from inventory"
else:
return f"Item {name} not found"
def update_quantity(self, name, new_quantity):
if name in self.inventory:
self.inventory[name]["quantity"] = new_quantity
return f"Updated {name} quantity to {new_quantity}"
else:
return f"Item {name} not found"
def get_item_info(self, name):
if name in self.inventory:
return self.inventory[name]
else:
return None
def display_inventory(self):
if not self.inventory:
return "Inventory is empty"
result = f"{'Item':<15} {'Price':<10} {'Quantity':<10}\n"
result += "-" * 35 + "\n"
for item, data in self.inventory.items():
result += f"{item:<15} ${data['price']:<9} {data['quantity']:<10}\n"
return result
def save_to_json(self, filename):
with open(filename, 'w') as f:
json.dump(self.inventory, f, indent=2)
return f"Inventory saved to {filename}"
def load_from_json(self, filename):
try:
with open(filename, 'r') as f:
self.inventory = json.load(f)
return f"Inventory loaded from {filename}"
except FileNotFoundError:
return f"File {filename} not found"
# Example usage
manager = InventoryManager()
# Add items
print(manager.add_item("laptop", 999, 10))
print(manager.add_item("mouse", 25, 50))
print(manager.add_item("keyboard", 75, 30))
# Display inventory
print("\nCurrent Inventory:")
print(manager.display_inventory())
# Update quantity
print(manager.update_quantity("laptop", 8))
# Get specific item info
laptop_info = manager.get_item_info("laptop")
print(f"\nLaptop info: {laptop_info}")
# Remove item
print(manager.remove_item("mouse"))
# Final inventory
print("\nFinal Inventory:")
print(manager.display_inventory())
Added laptop to inventory
Added mouse to inventory
Added keyboard to inventory
Current Inventory:
Item Price Quantity
-----------------------------------
laptop $999 10
mouse $25 50
keyboard $75 30
Updated laptop quantity to 8
Laptop info: {'price': 999, 'quantity': 8}
Removed mouse from inventory
Final Inventory:
Item Price Quantity
-----------------------------------
laptop $999 8
keyboard $75 30
Comparison
| Aspect | Dictionary Method | Class Method |
|---|---|---|
| Simplicity | Very Simple | More Complex |
| Reusability | Limited | High |
| Error Handling | Basic | Better |
| Extensibility | Limited | Easy to extend |
| Best For | Small projects | Large applications |
Key Features of JSON Inventory Management
Persistence Data is stored in JSON files and survives program restarts
Human-readable JSON format is easy to read and debug
Cross-platform JSON works across different programming languages
Lightweight Minimal overhead compared to databases
Conclusion
JSON provides an excellent solution for simple inventory management systems in Python. The dictionary approach works well for basic needs, while the class-based approach offers better organization and extensibility for larger applications. Both methods leverage JSON's simplicity and Python's built-in json module for effective data management.
