Python JSON Module: A Complete Tutorial for Beginners
Last updated 5 months, 1 week ago | 360 views 75 5

JSON (JavaScript Object Notation) is the most common format for data exchange on the web. It's lightweight, easy to read, and supported across many platforms. In Python, the json
module provides an easy way to encode and decode JSON data.
In this article, you’ll learn:
-
What JSON is and how it relates to Python
-
How to convert Python objects to JSON (
dump
,dumps
) -
How to convert JSON back to Python objects (
load
,loads
) -
Reading and writing JSON files
-
Custom encoding and decoding
-
Common use cases and pitfalls
What is JSON?
JSON is a text-based format for representing structured data. It’s widely used for APIs, configuration files, and data storage.
JSON Example:
{
"name": "Alice",
"age": 30,
"is_active": true,
"skills": ["Python", "Django"]
}
JSON maps naturally to Python data types:
JSON | Python |
---|---|
Object | dict |
Array | list |
String | str |
Number | int , float |
Boolean | bool |
Null | None |
Importing the json
Module
import json
Encoding Python Objects to JSON
Use json.dumps()
to convert a Python object to a JSON string.
person = {
"name": "Alice",
"age": 30,
"is_active": True
}
json_string = json.dumps(person)
print(json_string)
Output:
{"name": "Alice", "age": 30, "is_active": true}
Pretty-printed JSON:
print(json.dumps(person, indent=4))
Decoding JSON to Python Objects
Use json.loads()
to parse a JSON string into a Python object.
data = '{"name": "Alice", "age": 30, "is_active": true}'
python_obj = json.loads(data)
print(python_obj["name"])
Reading & Writing JSON to Files
✅ Writing to a File (json.dump()
)
person = {"name": "Bob", "age": 25}
with open("data.json", "w") as f:
json.dump(person, f, indent=2)
✅ Reading from a File (json.load()
)
with open("data.json", "r") as f:
person = json.load(f)
print(person["age"])
Real-World Example: Saving App Settings
settings = {
"theme": "dark",
"notifications": True,
"volume": 75
}
# Save settings to file
with open("settings.json", "w") as f:
json.dump(settings, f)
# Later, read them back
with open("settings.json", "r") as f:
loaded = json.load(f)
print(loaded["theme"]) # Output: dark
Custom Encoding: Non-Serializable Objects
JSON doesn't support all Python types like datetime
, set
, or custom classes.
Example: Handling datetime
objects
import json
from datetime import datetime
def custom_encoder(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError("Type not serializable")
data = {"created_at": datetime.now()}
json_string = json.dumps(data, default=custom_encoder)
print(json_string)
Convert Between JSON and Python Types
Python | JSON |
---|---|
dict |
Object |
list , tuple |
Array |
str |
String |
int , float |
Number |
True |
true |
False |
false |
None |
null |
Common Pitfalls
Mistake | Fix |
---|---|
❌ Serializing unsupported types (set , datetime ) |
Use default= parameter |
❌ Not closing file when writing JSON | Use with context manager |
❌ Confusing dump and dumps |
dump() = to file, dumps() = to string |
❌ Parsing invalid JSON | Validate or sanitize data before using loads() |
Tips for Working with JSON
-
✅ Use
indent=2
orindent=4
indump()
/dumps()
for pretty-printing -
✅ Always wrap file operations in
with
blocks -
✅ Use
json.loads()
with error handling (try
/except
) for untrusted data -
✅ Use
default=
injson.dumps()
to serialize custom objects -
✅ Prefer
json.load()
/json.dump()
for working directly with files
Summary Table
Function | Description |
---|---|
json.dumps(obj) |
Convert Python object → JSON string |
json.dump(obj, file) |
Write Python object → JSON file |
json.loads(string) |
Convert JSON string → Python object |
json.load(file) |
Read JSON file → Python object |
Conclusion
The json
module is essential for anyone working with web APIs, configurations, or data exchange in Python. By mastering its features, you can write cleaner, safer, and more interoperable code.
Whether you're building a web app, saving user settings, or working with APIs, the json
module is your go-to solution for data serialization in Python.