Reading & Writing JSON in Python
Python provides the built-in json module (no installation required).
There are 4 core functions you must master. Here is the easiest memory trick:
| Function | The Letter 's' Meaning | Where Data Comes From / Goes To |
|---|---|---|
json.loads() | Load String | Reads from a JSON text string in memory into a Python dict |
json.dumps() | Dump String | Converts a Python dict into a JSON text string |
json.load() | No 's' (File) | Reads from a JSON file on disk into a Python dict |
json.dump() | No 's' (File) | Writes a Python dict into a JSON file on disk |
1. Working with Strings in Memory: loads() & dumps()
Converting JSON String → Python Dictionary (loads)
When you receive JSON text from an API response, use json.loads() to convert it to a usable dictionary:
import json
# JSON text received from a web server
api_response_text = '{"name": "Sai Kumar", "role": "AI Engineer", "active": true}'
# Deserialize: String -> Python Dictionary
user_data = json.loads(api_response_text)
print(type(user_data)) # Output: <class 'dict'>
print(user_data["role"]) # Output: AI Engineer
print(user_data["active"]) # Output: True (converted to Python bool)
Converting Python Dictionary → JSON String (dumps)
When you want to send data to an API or print clean JSON text, use json.dumps():
import json
student = {
"name": "Kavya",
"marks": 94,
"passed": True
}
# Serialize: Python Dictionary -> JSON String
json_string = json.dumps(student, indent=2)
print(type(json_string)) # Output: <class 'str'>
print(json_string)
Output:
{
"name": "Kavya",
"marks": 94,
"passed": true
}
Why
indent=2?By default, json.dumps() produces one compact continuous line. Adding indent=2 or indent=4 formats the output with beautiful spacing (pretty-printing).
2. Working with Files on Disk: load() & dump()
Writing Data into a .json File (json.dump)
Use json.dump() with a with open(...) file handle:
import json
app_config = {
"app_name": "Think IT Telugu LMS",
"version": "2.4.0",
"theme": "dark",
"max_upload_mb": 50
}
# Save configuration directly into settings.json
with open("settings.json", "w") as file:
json.dump(app_config, file, indent=4)
print("✅ settings.json file saved successfully!")
Reading Data from a .json File (json.load)
Use json.load() to read an existing JSON file directly into a Python dictionary:
import json
with open("settings.json", "r") as file:
loaded_config = json.load(file)
print("Loaded App Name:", loaded_config["app_name"])
print("Active Theme:", loaded_config["theme"])
3. Common Beginner Mistake: load vs loads
The Extra 's' Matters!
json.loads(file)❌ Crashes! (loadsexpects a text string, not a file object).json.load(file)✅ Correct for files.json.load('{"id": 1}')❌ Crashes! (loadexpects an open file handle, not a string).json.loads('{"id": 1}')✅ Correct for strings.
Quick Summary
json.loads(str): Deserializes a JSON string into Python dict/list.json.dumps(obj): Serializes a Python dict/list into a JSON formatted string (indent=4for pretty-printing).json.load(file): Reads and parses JSON directly from an open file handle.json.dump(obj, file): Writes a Python data structure directly to an open disk file.- Memory vs. File: The
ssuffix stands for String (loads/dumps), while methods withoutsoperate on Files (load/dump).
What's Next?
Let's explore why LLMs, AI agents, and OpenAI/Anthropic APIs rely fundamentally on JSON in Why AI Uses JSON!