01 / 20
{ "k" : "v" }

Python
json Module

Learn to read and write JSON data using Python's built-in json module: serialization, deserialization, and real-world file handling.

Python

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.

Human-readable
Plain text you can open and understand in any editor
Language-agnostic
Used by Python, JavaScript, Java, Go, and virtually every language

JSON Data Types

JSON supports six core data types. Each maps directly to a Python type when loaded with the json module.

Object { }
Key-value pairs → Python dict
Array [ ]
Ordered list → Python list
String " "
Text → Python str
Number
Integer or float → Python int / float
Boolean
true / false → Python True / False
Null
null → Python None

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.

1
Built-in: available in every Python installation with import json
2
Safe parsing: validates structure and raises clear errors on bad input
3
Two directions: serialize (Python → JSON) and deserialize (JSON → Python)
4
File I/O: read from and write to .json files with one function call

The Four Core Functions

Python Object JSON String json.dumps() json.loads() Python Object JSON File json.dump() json.load() Strings (in memory) Files (on disk)

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.

import json # Python dict → JSON string data = {"name": "Alice", "age": 30, "honors": True} json_str = json.dumps(data) print(json_str) # '{"name": "Alice", "age": 30, "honors": true}' # JSON string → Python dict parsed = json.loads(json_str) print(parsed["name"]) # Alice

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.

import json # Write to a JSON file student = {"name": "Bob", "gpa": 3.8} with open("student.json", "w") as f: json.dump(student, f) # Read from a JSON file with open("student.json", "r") as f: loaded = json.load(f) print(loaded["gpa"]) # 3.8

How to Apply: Step by Step

1
Import: write import json at the top of your script
2
Choose direction: are you reading JSON or writing JSON?
3
Choose target: working with a string? Use dumps/loads. Working with a file? Use dump/load.
4
Open file safely: if using files, wrap in a with open(...) block
5
Use the result: the returned object is a normal Python dict or list: index, loop, and manipulate as usual

Pretty Printing with indent

By default, dumps() produces compact output. Pass the indent parameter to get nicely formatted, human-readable JSON.

import json data = {"course": "CS101", "students": ["Alice", "Bob"]} # Compact (default) print(json.dumps(data)) # {"course": "CS101", "students": ["Alice", "Bob"]} # Pretty-printed print(json.dumps(data, indent=2)) # { # "course": "CS101", # "students": [ # "Alice", # "Bob" # ] # }

Example 1: Writing a Config File

Save application settings as a JSON file that both humans and programs can read.

import json config = { "theme": "dark", "font_size": 14, "auto_save": True, "recent_files": ["hw1.py", "hw2.py"] } with open("config.json", "w") as f: json.dump(config, f, indent=4) print("Config saved!")

Example 2: Read, Modify, Write

A common pattern: load existing JSON, update values, then save it back.

import json # 1. Read existing config with open("config.json", "r") as f: config = json.load(f) # 2. Modify a value config["font_size"] = 16 config["recent_files"].append("hw3.py") # 3. Write back with open("config.json", "w") as f: json.dump(config, f, indent=4)

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.

import json # Simulated API response (a JSON string) response = '{"status": "ok", "temp": 72.5, "unit": "F"}' # Parse the JSON string weather = json.loads(response) print(weather["status"]) # ok print(weather["temp"]) # 72.5 print(type(weather)) # <class 'dict'>

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

✕ Mixing up dump/dumps
Using dumps() when you meant to write to a file, or dump() with a string. Remember: "s" = string.
✕ Forgetting quotes in JSON
JSON keys must use double quotes. Single quotes or unquoted keys cause a JSONDecodeError.
✕ Using eval() to parse JSON
Never use eval() on JSON: it is a security risk. Always use json.loads() for safe parsing.

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

What does the program print?

Question 4 of 5

Which parameter makes json.dumps() output nicely formatted, indented JSON?

Question 5 of 5

What is the output?