Python
json Module
Learn to read and write JSON data using Python's built-in json module: serialization, deserialization, and real-world file handling.
What is JSON?
JSON stands for JavaScript Object Notation. It is a lightweight, text-based data format used to store and exchange structured data between systems: APIs, config files, databases, and more.
JSON Data Types
JSON supports six core data types. Each maps directly to a Python type when loaded with the json module.
Why the json Module?
Python ships with a built-in json module: no installation required. It handles converting between Python objects and JSON text safely and efficiently.
The Four Core Functions
dumps() and loads(): Strings
json.dumps() converts a Python object to a JSON-formatted string. json.loads() parses a JSON string back into a Python object.
dump vs dumps: Key Distinction
| dumps() / loads() | dump() / load() | |
|---|---|---|
| Target | String in memory | File on disk |
| Second argument | None | File object |
| Returns | A string / Python object | None (writes to file) / Python object |
| Use case | APIs, logging, debugging | Config files, data storage |
| Memory hint | "s" = string | No "s" = file stream |
dump() and load(): Files
json.dump() writes Python data directly to a file. json.load() reads JSON from a file and returns a Python object.
How to Apply: Step by Step
Pretty Printing with indent
By default, dumps() produces compact output. Pass the indent parameter to get nicely formatted, human-readable JSON.
Example 1: Writing a Config File
Save application settings as a JSON file that both humans and programs can read.
Example 2: Read, Modify, Write
A common pattern: load existing JSON, update values, then save it back.
Example 3: Parsing an API Response
Web APIs often return JSON strings. Use json.loads() to convert the response into a Python dict you can work with.
Python ↔ JSON Type Mapping
| Python Type | JSON Type | Example |
|---|---|---|
| dict | object | {"key": "val"} |
| list, tuple | array | [1, 2, 3] |
| str | string | "hello" |
| int, float | number | 42, 3.14 |
| True / False | true / false | true |
| None | null | null |
Common Mistakes
Question 1 of 5
Which function converts a Python dict into a JSON-formatted string?
Question 2 of 5
What Python type does json.loads('{"a": null}') produce for the value of key "a"?
Question 3 of 5
Consider this code:
What does the program print?
Question 4 of 5
Which parameter makes json.dumps() output nicely formatted, indented JSON?
Question 5 of 5
Consider this code:
The file data.json contains: {"score": 95, "passed": true}
What is the output?