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
Read a JSON file
Section titled “Read a JSON file”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.
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']}')
Add an element to the JSON file
Section titled “Add an element to the JSON file”Load the products from the file, add a new product to the end of the list and save everything again, overwriting the original file.
import json
# New product to addnew_product = {'name': 'Keyboard', 'price': 19.99}
# Read current productswith open('./document/products.json', 'r') as file:products = json.load(file)
# Add the new productproducts.append(new_product)
# Save the updated listwith open('./document/products.json', 'w') as file:json.dump(products, file, indent=2)
Overwrite a JSON file
Section titled “Overwrite a JSON file”Overwrite the entire products.json file with a new list of products. Use the “w” mode to replace all previous content.
import json
# New products listproducts = [{'name': 'Mouse', 'price': 9.99},{'name': 'Monitor', 'price': 129.99}]
# Save the new list in the filewith open('./document/products.json', 'w') as file:json.dump(products, file, indent=2)