Inventory Management with JSON in Python


Inventory Management with JSON : Introduction

Any firm that handles and tracks items or products needs to have effective inventory management. In order to guarantee that there is a sufficient supply of goods for clients and avoid overstocking or stockouts, it entails the process of monitoring and controlling the input and outflow of commodities. We'll look at using JSON for inventory management in Python in this tutorial.

Inventory Management with JSON

Definition

JSON, or JavaScript Object Notation, is a simple data exchange format that is simple for both humans and robots to read and write. For data sharing between several applications and computer languages, it is commonly utilised. JSON is a text format that uses key-value pairs and has syntax that is comparable to a Python dictionary.

Syntax

{"Key 1":"value 1",
"Key 2":"value 2",
.
.
"Key n":"value n"}

JSON's syntax is simple to read and comprehend. It is made up of key-value pairs encased in curly braces. A comma is used to separate each key-value pair. The value can be any acceptable JSON data type, including a string, number, boolean, array, or another JSON object. The key is always a string.

Algorithm

  • Step 1 − For the objects in the inventory, create a JSON object.

  • Step 2 − Open a file or API and read the JSON data.

  • Step 3 − Adjust the inventory data as necessary (for example, by adding new items and updating quantities).

  • Step 4 − Updated inventory data should be written back to the file or API.

  • Step 5 − Repeat the process as needed.

Approach

  • Approach 1 − Inventory Management with JSON using Python's in-built JSON module

  • Approach 2 − Inventory Management with JSON using a custom Inventory class

Approach 1: Inventory Management with JSON using Python's in-built JSON module

In this approach, we'll read and write data to a JSON file using the built-in JSON module of Python. To add, remove, and examine the objects in the inventory, we will construct a straightforward inventory management system. Here is the key −

Example

import json

# Load the inventory data from the file
with open('inventory.json', 'r') as f:
   inventory = json.load(f)

# Function to add a new item to the inventory
def add_item():
   item_name = input('Enter item name: ')
   item_price = int(input('Enter item price: '))
   item_quantity = int(input('Enter item quantity: '))
   inventory[item_name] = {
      'price': item_price,
      'quantity': item_quantity
   }
   save_inventory()

# Function to remove an item from the inventory
def remove_item():
   item_name = input('Enter item name: ')
   if item_name in inventory:
      del inventory[item_name]
      save_inventory()
   else:
      print('Item not found in inventory')

# Function to display the inventory
def display_inventory():
   print('{:<15} {:<10} {:<10}'.format('Item', 'Price', 'Quantity'))
   for item_name, item_data in inventory.items():
      print('{:<15} {:<10} {:<10}'.format(item_name, item_data['price'], item_data['quantity']))

# Function to save the inventory to the file
def save_inventory():
   with open('inventory.json', 'w') as f:
      json.dump(inventory, f)

# Main program loop
while True:
   print('1. Add item')
   print('2. Remove item')
   print('3. Display inventory')
   print('4. Exit')
   choice = int(input('Enter choice: '))
   if choice == 1:
      add_item()
   elif choice == 2:
      remove_item()
   elif choice == 3:
      display_inventory()
   elif choice == 4:
      break
   else:
      print('Invalid choice')

Output

1. Add item
2. Remove item
3. Display inventory
4. Exit
Enter choice: 1
Enter item name: Apple
Enter item price: 10
Enter item quantity: 20
1. Add item
2. Remove item
3. Display inventory
4. Exit
Enter choice: 1
Enter item name: Banana
Enter item price: 20
Enter item quantity: 30
1. Add item
2. Remove item
3. Display inventory
4. Exit
Enter choice: 3
Item           Price      Quantity  
Apple          10         20        
Banana         20         30        
1. Add item
2. Remove item
3. Display inventory
4. Exit
Enter choice: 2
Enter item name: Apple
1. Add item
2. Remove item
3. Display inventory
4. Exit
Enter choice: 3
Item           Price      Quantity  
Banana         20         30        
1. Add item
2. Remove item
3. Display inventory
4. Exit
Enter choice: 4

Approach 2: Inventory Management with JSON using a custom Inventory class

In this approach, we'll build a special Inventory class that will contain the inventory data and offer methods for adding, removing, and viewing inventory items. The Python language's built-in JSON module will be used to read and write data to JSON files. Here is the key −

Example

import json

class Inventory:
def _init_(self, filename):
   self.filename = filename
   # Load the inventory data from the file
   with open(filename, 'r') as f:
      self.data = json.load(f)

def add_item(self, name, price, quantity):
   self.data[name] = {'price': price, 'quantity': quantity}
   self.save()

def remove_item(self, name):
   if name in self.data:
      del self.data[name]
      self.save()
   else:
      print('Item not found in inventory')

def display_inventory(self):
   print('{:<15} {:<10} {:<10}'.format('Item', 'Price', 'Quantity'))
   for item_name, item_data in self.data.items():
      print('{:<15} {:<10} {:<10}'.format(item_name, item_data['price'], item_data['quantity']))

def save(self):
   with open(self.filename, 'w') as f:
      json.dump(self.data, f)
#Create an inventory object
inventory = Inventory('inventory.json')

#Main program loop
while True:
print('1. Add item')
print('2. Remove item')
print('3. Display inventory')
print('4. Exit')
choice = int(input('Enter choice: '))
if choice == 1:
name = input('Enter item name: ')
price = int(input('Enter item price: '))
quantity = int(input('Enter item quantity: '))
inventory.add_item(name, price, quantity)
elif choice == 2:
name = input('Enter item name: ')
inventory.remove_item(name)
elif choice == 3:
inventory.display_inventory()
elif choice == 4:
break
else:
print('Invalid choice')

Output

1. Add item
2. Remove item
3. Display inventory
4. Exit
Enter choice: 1
Enter item name: Apple
Enter item price: 10
Enter item quantity: 20
1. Add item
2. Remove item
3. Display inventory
4. Exit
Enter choice: 1
Enter item name: Banana
Enter item price: 20
Enter item quantity: 30
1. Add item
2. Remove item
3. Display inventory
4. Exit
Enter choice: 3
Item           Price      Quantity  
Apple          10         20        
Banana         20         30        
1. Add item
2. Remove item
3. Display inventory
4. Exit
Enter choice: 2
Enter item name: Apple
1. Add item
2. Remove item
3. Display inventory
4. Exit
Enter choice: 3
Item           Price      Quantity  
Banana         20         30        
1. Add item
2. Remove item
3. Display inventory
4. Exit
Enter choice: 4

Conclusion

In conclusion, inventory control is a crucial part of managing a corporation. A straightforward and efficient inventory management system that can store and handle inventory data simply can be made using Python and JSON. In this example, we've shown how to use two different Python implementation strategies for JSON-based inventory management.The first method created a JSON file by writing the inventory data to a dictionary. Although this strategy was straightforward and simple to use, it had significant drawbacks. For instance, tracking inventory changes over time or supporting multiple inventories were not supported.The second technique had methods for adding, deleting, and displaying things and used a class to contain the inventory data.

This method was easier to expand to handle multiple inventories and maintaining inventory history since it was more flexible and extendable than the first method.The choice of strategy will rely on the unique requirements of the inventory management system. Both approaches have advantages and disadvantages. Whatever method is employed, JSON and Python offer a potent pairing for maintaining inventory data that is both straightforward and efficient.

Updated on: 12-Oct-2023

146 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements