0
0
Pythonprogramming~30 mins

Working with JSON files in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Working with JSON files
📖 Scenario: You are managing a small library's book records. The library stores book information in JSON files. You want to read, update, and save this data using Python.
🎯 Goal: Learn how to load JSON data from a file, update it, and save it back to a JSON file using Python.
📋 What You'll Learn
Create a JSON data structure representing books
Load JSON data from a file
Update the JSON data by adding a new book
Save the updated JSON data back to a file
Print the updated JSON data
💡 Why This Matters
🌍 Real World
Many applications store data in JSON files because JSON is easy to read and write. Managing JSON files is common in web apps, configuration files, and data exchange.
💼 Career
Knowing how to work with JSON files is important for software developers, data analysts, and anyone working with APIs or configuration management.
Progress0 / 4 steps
1
Create initial JSON data
Create a variable called books that holds a list of dictionaries. Each dictionary should represent a book with these exact keys and values: {"title": "The Hobbit", "author": "J.R.R. Tolkien", "year": 1937} and {"title": "1984", "author": "George Orwell", "year": 1949}.
Python
Need a hint?

Use a list with two dictionaries inside. Each dictionary has keys: title, author, and year.

2
Save JSON data to a file
Import the json module. Then open a file called library.json in write mode and save the books list to this file using json.dump().
Python
Need a hint?

Use import json. Then open the file with open("library.json", "w") and use json.dump(books, file) to save.

3
Load JSON data from the file and update it
Open the file library.json in read mode and load the JSON data into a variable called loaded_books using json.load(). Then add a new book dictionary {"title": "To Kill a Mockingbird", "author": "Harper Lee", "year": 1960} to loaded_books.
Python
Need a hint?

Use with open("library.json", "r") as file and loaded_books = json.load(file). Then use loaded_books.append(...) to add the new book.

4
Save updated data and print it
Open library.json in write mode again and save the updated loaded_books list using json.dump(). Then print loaded_books to show the updated list.
Python
Need a hint?

Open the file with open("library.json", "w") and save loaded_books with json.dump(). Then print loaded_books.