Learn how to use JSON (JavaScript Object Notation) for data interchange and manipulate it using Python's json module. This lab will also introduce how to integrate JSON with basic OOP structures in Python.
Ensure that you are signed into your GitHub account
Join the GitHub Classroom and accept this assignment: Project 14 - Library System
Clone the repository to your computer using GitHub Desktop or open it online using Codespaces
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999.
JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.
Human-readable: JSON is written in key/value pairs and is easy to read compared to other data formats like XML.
Lightweight: JSON has a smaller footprint, making it ideal for data interchange over the internet.
Language Independence: JSON is supported by many programming languages, making it a versatile choice for web APIs and configuration files.
Easy to integrate: Many web services offer JSON APIs, and it is the backbone of most modern web and mobile applications.
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realised as an object, record, struct, dictionary, hash table, etc...
An ordered list of values. In most languages, this is realised as an array, vector, list, or sequence.
Data is in name/value pairs:
{
"name": "Alice"
}
Data is separated by commas:
{
"name": "Alice",
"age": 25,
"city": "Sydney"
}
Curly braces hold objects {}:
{
"employee": {
"name": "Alice",
"age": 25,
"city": "Sydney"
}
}
Square brackets hold arrays []:
{
"names": ["Alice", "Bob", "Charlie"]
}
Keys must be strings, and values can be strings, numbers, objects, arrays, true, false, or null:
{
"name": "Alice",
"is_student": true,
"grades": [88, 90, 92],
"address": {
"street": "123 Apple St",
"city": "Sydney"
},
"pets": null
}
Python's json module provides an easy way to encode and decode JSON data. Below are some of the most common functions:
json.dump(): Saves a Python object as JSON text directly into a file.
json.dumps(): Converts a Python object to a JSON string, not involving files directly.
json.load(): Reads JSON text from a file and converts it into a Python object.
json.loads(): Converts a JSON string to a Python object, without reading from a file.
This example demonstrates how to read JSON data from a file and convert it into a Python dictionary:
This example shows how to convert a Python dictionary into JSON and save it to a file:
In Python, the ** operator is used to unpack dictionaries into keyword arguments. This feature is especially useful in OOP when you need to create objects from data that has been stored in a dictionary or after retrieving structured data from files like JSON.
When a dictionary represents an object's attributes, you can pass it to the class constructor using the ** operator. This allows for dynamic object creation based on the dictionary's key-value pairs, where keys correspond to argument names expected by the constructor.
This example will ask the user repeatedly for names and phone numbers, storing them in a list of dictionaries. Once the user indicates they are done (by entering nothing), the list will be written to a JSON file.
This example builds on the concept of a text-based Todo List, enhancing it with OOP principles and JSON for saving and loading tasks. We'll define a TodoList class for managing tasks and a Task class for individual tasks.
Open a File: We open a file called todo_list.json in write mode. If the file doesn't exist, Python will create it.
Convert Tasks to Dictionary: Before saving tasks, we convert each task object into a dictionary format (__dict__).
This is because JSON can only directly handle basic data types like strings, numbers, lists, and dictionaries, not custom objects like Task.
Save to File: We use json.dump() to write the list of task dictionaries to the file. The indent=4 parameter makes the JSON file easier to read by adding indentation to each line.
Open the File: We try to open the file todo_list.json in read mode to get the tasks saved previously.
Read and Convert: We use json.load() to convert the JSON file back into a list of dictionaries. We then convert each dictionary back into a Task object. We use dictionary unpacking here (with the ** operator) passing the keys and values as arguments to the Task constructor.
Handle No File: If the file does not exist (for instance, when you run the program for the first time), Python raises a FileNotFoundError. We catch this error and print a message that no saved tasks were found, which prevents the program from crashing.
Open lab2.py
Complete the music catalog manager program by programming the following functions:
Create Song Class: Define the Song class with attributes for title, artist, album, and year, and provide a constructor for initialisation.
Add Song: Prompt for song details, create a Song object, add to catalog, and save to JSON.
List Songs: Display each song in the catalog using their string representations.
Search Songs: Get user input for search term and show all songs that match the criteria.
Delete Song: Remove songs matching a user-provided title from the catalog and update the JSON file.
Save Catalog: Serialize the catalog of Song objects to a JSON file.
Load Catalog: Deserialize JSON back into Song objects and populate the catalog, handle file not found errors.
Commit and push your code