Module 5 Lesson 4: Handling JSON Files
·Programming

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 json Module: Serializing and Deserializing.
  • load vs. loads: Files vs. Strings.
  • dump vs. 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?

  1. Nesting: JSON can store a "User" who has a "Profile" which contains a "List of Posts." CSVs can't do this easily.
  2. Type Safety: JSON knows the difference between a number (15) and a string ("15").
  3. The API Standard: If you want to talk to Spotify, Twitter, or ChatGPT, you will use JSON.

Practice Exercise: The Game State Saver

  1. Create a dictionary representing a game character (name, health, inventory list, and stats dictionary).
  2. Save this dictionary to a file named save_game.json.
  3. Write a second script that reads the file back into a variable.
  4. Increase the character's health by 20 and print the updated dictionary.

Quick Knowledge Check

  1. What does JSON stand for?
  2. What is the difference between json.load() and json.loads()?
  3. Why would you use indent=4 when dumping JSON?
  4. Can a JSON file store a Python list?

Key Takeaways

  • JSON is the most common data format for web APIs.
  • load/dump are for files; loads/dumps are for strings.
  • JSON is more flexible than CSV for complex, nested data.
  • The json module 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!

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn