Skip to content

Reading and writing JSON files

JSON files (JavaScript Object Notation) are used for storing and transporting structured data. Unlike TXT or CSV, they can represent objects, nested lists and more complex hierarchies. Python provides the json module for handling them.

We have the following project structure:

  • Directorysrc
    • read_json.py
    • write_json.py
    • rewrite_json.py
  • Directorydocs
    • products.json

Open the products.json file in read mode (“r”), load its content as a list of dictionaries and then print the name and price of each product.

read_json.py
import json
with open('./document/products.json', mode='r') as file:
    products = json.load(file)
    for product in products:
        print(f'The product {product['name']} priced at {product['price']}')

Load the products from the file, add a new product to the end of the list and save everything again, overwriting the original file.

read_json.py
import json
# New product to add
new_product = {'name': 'Keyboard', 'price': 19.99}
# Read current products
with open('./document/products.json', 'r') as file:
products = json.load(file)
# Add the new product
products.append(new_product)
# Save the updated list
with open('./document/products.json', 'w') as file:
json.dump(products, file, indent=2)

Overwrite the entire products.json file with a new list of products. Use the “w” mode to replace all previous content.

read_json.py
import json
# New products list
products = [
{'name': 'Mouse', 'price': 9.99},
{'name': 'Monitor', 'price': 129.99}
]
# Save the new list in the file
with open('./document/products.json', 'w') as file:
json.dump(products, file, indent=2)