Module 5 Lesson 4: Handling JSON Files
Master the language of the web. Learn how to parse JSON data into Python dictionaries and save complex objects into JSON files.
Module 5 Lesson 4: Handling JSON Files
JSON stands for JavaScript Object Notation. Despite the name, it is used by almost every programming language in the world, including Python. It is the gold standard for sending data over the internet and storing complex configurations.
Lesson Overview
In this lesson, we will cover:
- What is JSON?: Keys, values, and nesting.
- The
jsonModule: Serializing and Deserializing. loadvs.loads: Files vs. Strings.dumpvs.dumps: Saving vs. Displaying.
1. What is JSON?
JSON looks almost identical to a Python dictionary. It supports strings, numbers, booleans, lists, and other objects.
Example config.json:
{
"app_name": "WeatherBuddy",
"version": 1.5,
"active": true,
"features": ["GPS", "Alerts", "Cloud Store"]
}
2. Reading JSON (load and loads)
json.load(file): Reads JSON from a file object.json.loads(string): Reads JSON from a string (the "s" stands for "string").
import json
# Reading from a file
with open("config.json", "r") as file:
data = json.load(file)
print(data["app_name"]) # Output: WeatherBuddy
# Reading from a string
json_str = '{"user": "Alex", "id": 1}'
user_data = json.loads(json_str)
print(user_data["user"]) # Output: Alex
3. Writing JSON (dump and dumps)
json.dump(data, file): Saves a dictionary directly into a file.json.dumps(data): Converts a dictionary into a JSON string.
user = {"name": "Sara", "level": 10, "is_pro": False}
# Save to file with pretty indentations
with open("user.json", "w") as file:
json.dump(user, file, indent=4)
(Note: indent=4 makes the file readable for humans!)
4. Why JSON Over CSV?
- Nesting: JSON can store a "User" who has a "Profile" which contains a "List of Posts." CSVs can't do this easily.
- Type Safety: JSON knows the difference between a number (
15) and a string ("15"). - The API Standard: If you want to talk to Spotify, Twitter, or ChatGPT, you will use JSON.
Practice Exercise: The Game State Saver
- Create a dictionary representing a game character (name, health, inventory list, and stats dictionary).
- Save this dictionary to a file named
save_game.json. - Write a second script that reads the file back into a variable.
- Increase the character's health by 20 and print the updated dictionary.
Quick Knowledge Check
- What does JSON stand for?
- What is the difference between
json.load()andjson.loads()? - Why would you use
indent=4when dumping JSON? - Can a JSON file store a Python list?
Key Takeaways
- JSON is the most common data format for web APIs.
load/dumpare for files;loads/dumpsare for strings.- JSON is more flexible than CSV for complex, nested data.
- The
jsonmodule makes conversion to/from Python dictionaries instant.
What’s Next?
We’ve used the with statement in every lesson so far. But what exactly is it doing? In Lesson 5, we’ll take a Deep Dive into the with Statement and learn why it’s Python’s secret weapon for resource management!