Lesson 17: JSON Handling in Python

How to read, write, and manipulate JSON data using Python

What Is JSON?

JSON (JavaScript Object Notation) is a lightweight data format used for storing and exchanging data. It is widely used in APIs, configuration files, and web applications.

Example JSON

{
    "name": "Alice",
    "age": 30,
    "languages": ["Python", "JavaScript"]
}

The json Module

Python includes a built‑in json module for working with JSON data.

Loading JSON from a String

import json

json_str = '{"name": "Alice", "age": 30}'
data = json.loads(json_str)

print(data["name"])   # Alice

Loading JSON from a File

import json

with open("data.json", "r") as file:
    data = json.load(file)

print(data)

Writing JSON to a File

import json

person = {"name": "Bob", "age": 25}

with open("output.json", "w") as file:
    json.dump(person, file)

Pretty‑Printing JSON

You can format JSON output to make it easier to read:

print(json.dumps(person, indent=4))

Converting Python Objects to JSON

Use json.dumps() to convert Python objects into JSON strings:

data = {"numbers": [1, 2, 3]}
json_text = json.dumps(data)
print(json_text)

Handling Complex Data Types

JSON supports only basic types (strings, numbers, lists, dicts). To serialize custom objects, you must convert them manually:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 30)

json_text = json.dumps(p.__dict__)
print(json_text)

Common JSON Pitfalls

Why JSON Matters

Next Steps

Now that you can work with JSON, you're ready to explore how to build simple command‑line tools in Lesson 18: Building Simple Command‑Line Tools.

← Back to Lesson Index