Statistical Analysis of JSON Data

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to perform statistical analysis on JSON data using Python. You will parse a JSON file containing user study data, extract specific information, and calculate the number of courses studied and the total number of minutes studied for a given user.

👀 Preview

$ python3 analysis.py
(4, 12)

ðŸŽŊ Tasks

In this project, you will learn:

  • How to read and parse a JSON file using Python
  • How to extract specific data items from the JSON data
  • How to perform statistical analysis on the extracted data

🏆 Achievements

After completing this project, you will be able to:

  • Develop a Python function to analyze JSON data
  • Calculate the number of courses studied and the total minutes studied for a given user
  • Apply basic data analysis techniques to extract insights from structured data

Implement the analysis Function

In this step, you will implement the analysis function to parse the JSON file and analyze the user data.

  1. Add the following code to the analysis.py file:
import json


def analysis(file, user_id):
    """
    Load json into this function and parse the data
    """
    with open(file, "r", encoding="utf-8") as f:
        data = json.load(f)

    courses_studied = 0
    total_minutes = 0

    for item in data:
        if item["user_id"] == user_id:
            courses_studied += 1
            total_minutes += item["minutes"]

    return courses_studied, total_minutes
  1. The analysis function takes two parameters:

    • file: the name of the JSON file containing the user study data
    • user_id: the ID of the user whose data you want to analyze
  2. The function reads the JSON file, iterates through the data, and counts the number of courses studied and the total number of minutes studied for the specified user.

  3. The function returns two values:

    • courses_studied: the number of courses studied by the specified user
    • total_minutes: the total number of minutes studied by the specified user

Test the analysis Function

In this step, you will test the analysis function by calling it with the provided user_study.json file and a user ID.

  1. Add the following code at the end of the analysis.py file:
if __name__ == "__main__":
    print(analysis("user_study.json", 131866))
  1. Save the analysis.py file.
  2. Run the analysis.py script from the terminal:
python3 analysis.py
  1. The output should be a tuple containing the number of courses studied and the total number of minutes studied for the user with ID 131866.
(4, 12)

Congratulations! You have completed the project. You can now use the analysis function to analyze the user study data in the user_study.json file.

âœĻ 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