Project · Reading log
Summarize a small JSON reading log.
Build a report from a list of JSON records. Decode the data, select the finished books, and total their pages. Keep the summarizing logic in a function that accepts a list, so you can try it with other data.
Use a small input where you already know the answer. The starting log has one finished book. Add another finished record and verify that the count and page total change while the unfinished record stays excluded.
Each JSON object becomes a dictionary.
Try it yourself
Add a finished book of 80 pages to the raw log. Confirm that your report also returns (0, 0) for an empty list without printing any extra lines. Then check the updated output.
Target output
Finished: 2
Pages: 200Show a hint
JSON uses lowercase true. You can check the empty case with assert report([]) == (0, 0).
Ready
Run your code to see the output here.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
import json
raw_log = '[{"pages": 120, "finished": true}, {"pages": 90, "finished": false}, {"pages": 80, "finished": true}]'
def report(books):
finished = [book for book in books if book["finished"]]
return len(finished), sum(book["pages"] for book in finished)
assert report([]) == (0, 0)
count, pages = report(json.loads(raw_log))
print(f"Finished: {count}")
print(f"Pages: {pages}")