Extracting and Sorting Movie Data from JSON

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to extract movie information from a JSON file and print the movie names and release dates in ascending order of release date. This project will help you develop skills in working with JSON data and file handling in Python.

👀 Preview

movie: The Shawshank Redemption, published: 1994-10-14
movie: Pulp Fiction, published: 1994-10-14
movie: The Dark Knight, published: 2008-07-18
movie: Inception, published: 2010-07-16

ðŸŽŊ Tasks

In this project, you will learn:

  • How to read and parse JSON data using the json module in Python
  • How to extract specific information from a JSON data structure
  • How to sort a list of dictionaries based on a specific key
  • How to print formatted output to the console

🏆 Achievements

After completing this project, you will be able to:

  • Understand how to work with JSON data in Python
  • Extract and manipulate data from a JSON file
  • Sort data based on a specific criteria
  • Present the extracted information in a readable format

Implement the extract_movie_info Function

In this step, you will implement the extract_movie_info function to extract the movie names and release dates from the movie.json file.

  1. Open the movie.py file.
  2. Inside the extract_movie_info function, add the following code to read the movie data from the movie.json file, sort the movies by release date, and print the movie names and release dates:
def extract_movie_info(file_path):
    with open(file_path, "r") as file:
        data = json.load(file)
        movies = data["movies"]
        sorted_movies = sorted(movies, key=lambda x: x["published_at"])

        for movie in sorted_movies:
            name = movie["name"]
            published_at = movie["published_at"]
            print(f"movie: {name}, published: {published_at}")

Run the Script

In this step, you will run the movie.py script to extract the movie information.

  1. Open a terminal and navigate to the /home/labex/project directory.
  2. Run the movie.py script using the following command:
python3 movie.py

You should see the following output:

movie: The Shawshank Redemption, published: 1994-10-14
movie: Pulp Fiction, published: 1994-10-14
movie: The Dark Knight, published: 2008-07-18
movie: Inception, published: 2010-07-16

Congratulations! You have successfully completed the project. You have implemented the extract_movie_info function to extract and print the movie names and release dates from the movie.json file in ascending order of release date.

âœĻ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like