← Back to Python Course | Chapter 9: File Handling | Lesson 5 of 6

Python JSON Files

The json Module

JSON (JavaScript Object Notation) is a lightweight, text-based data format that's become the standard for exchanging structured data over the web, and Python's built-in json module converts between it and native Python objects with no external dependencies.

Example: The json Module

python
import json
data = {"name": "Alex"}
print(json.dumps(data))

Reading JSON Files

json.load(file_object) reads an open file's JSON content and parses it directly into Python objects (dicts, lists, strings, numbers) in one call -- this is different from json.loads(), which parses a JSON string you already have in memory rather than a file.

Example: Reading JSON Files

python
import json
with open("data.json", "w") as f:
    json.dump({"name": "Alex"}, f)
with open("data.json", "r") as f:
    data = json.load(f)
print(data)

Writing JSON Files

json.dump(data, file_object) serializes a Python dict or list and writes the resulting JSON text directly to an open file -- pass indent=2 as an extra argument if you want the output formatted for human readability rather than a single dense line.

Example: Writing JSON Files

python
import json
data = {"name": "Alex", "age": 30}
with open("data.json", "w") as f:
    json.dump(data, f, indent=2)
with open("data.json") as f:
    print(f.read())

JSON Data Types Conversion

The json module maps types automatically in both directions: Python's None becomes JSON's null, True/False become true/false, and dicts/lists map to JSON objects/arrays -- but Python-specific types like sets or datetime objects aren't JSON-serializable by default and need custom handling.

Example: JSON Data Types Conversion

python
import json
data = {"active": True, "value": None, "items": [1, 2]}
text = json.dumps(data)
print(text)

Custom JSON Object Hooks

The object_hook parameter to json.load()/loads() lets you supply a function that runs on every parsed JSON object as it's decoded, which is how you can automatically convert plain dicts into custom Python objects (like turning {x:1,y:2} into a Point instance) during parsing.

Example: Custom JSON Object Hooks

python
import json

def as_point(d):
    if "x" in d and "y" in d:
        return (d["x"], d["y"])
    return d

result = json.loads('{"x": 1, "y": 2}', object_hook=as_point)
print(result)
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.