# q4_2.py
import json
import matplotlib.pyplot as plt

# 1. 读取文件
with open("movies.json", "r", encoding="utf-8") as f:
    data = json.load(f)

# 2. 安全提取电影列表
if type(data) is dict and "movies" in data:
    movies = data["movies"]
else:
    movies = []

# 3. 准备数据
x_data = []
y_data = []

for item in movies:
    # 这一行彻底防止报错
    if type(item) is dict:
        x_data.append(item["duration"])
        y_data.append(item["rating"])

# 4. 画图（题目全部要求）
plt.scatter(x_data, y_data, color="red", alpha=0.6)
plt.title("时长与评分关系散点图")
plt.xlabel("时长（分钟）")
plt.ylabel("评分")
plt.savefig("q4_2_scatter.png", dpi=150)
plt.close()

print("运行成功！")