Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 6 · The json Module

The json Module

On this pageJSON in PythonParse JSON — Convert from JSON to PythonConvert from Python to JSONFormatting the Result

The json module allows you to work with JSON data—a lightweight format widely used for sharing data between systems and APIs.

It helps you convert between Python objects and JSON text easily.

JSON in Python

JSON (JavaScript Object Notation) represents data as text but looks similar to Python dictionaries. This makes conversion between the two very natural in Python.

Parse JSON — Convert from JSON to Python

json.loads() parses JSON text into the corresponding Python values: an object becomes a dictionary, an array becomes a list, and scalar values become the corresponding Python scalars. Here the input is an object:

import json

data = '{"name": "Alice", "age": 25, "city": "Paris"}'
person = json.loads(data)
print(person["city"])
Listing 258 — Parse JSON — Convert from JSON to Python

Output

Paris

Convert from Python to JSON

You can use json.dumps() to turn Python data structures into JSON strings.

student = {
    "name": "Bob",
    "age": 22,
    "courses": ["Math", "AI"]
}

json_string = json.dumps(student)
print(json_string)
Listing 259 — Convert from Python to JSON

Output

{"name": "Bob", "age": 22, "courses": ["Math", "AI"]}

Formatting the Result

You can make JSON output more readable by adding indentation and sorting keys.

print(json.dumps(student, indent=4, sort_keys=True))
Listing 260 — Formatting the Result

Output

{
    "age": 22,
    "courses": [
        "Math",
        "AI"
    ],
    "name": "Bob"
}

The json module is essential for saving configurations, web communication, and data storage.