Working with JSON in Python: A Practical Guide
Learn how to read, write, and parse JSON in Python using the built-in json module. Includes real examples for APIs, config files, and data storage every developer needs.
JSON in Python is something you’ll work with constantly — APIs return JSON, config files use JSON, databases store JSON. The good news is Python’s built-in json module makes it simple. No installation needed.
Reading JSON: Parsing Strings and Files
JSON looks like a Python dictionary, but it’s a string. The json module converts between the two.
import json
# Parse a JSON string
json_string = '{"name": "Kaikobud", "age": 28, "skills": ["Python", "Go"]}'
data = json.loads(json_string) # loads = "load string"
print(data["name"]) # Kaikobud
print(data["skills"]) # ['Python', 'Go']
To read JSON from a file:
with open("config.json", "r") as f:
config = json.load(f) # load (no 's') reads from a file object
print(config["database_host"])
The pattern is simple: json.loads() for strings, json.load() for files.
Writing JSON: Converting Python to JSON
import json
user = {
"id": 1,
"name": "Kaikobud",
"active": True,
"score": 9.5
}
# Convert to JSON string
json_string = json.dumps(user, indent=2)
print(json_string)
# Write to a file
with open("output.json", "w") as f:
json.dump(user, f, indent=2)
The indent=2 parameter makes the output human-readable. Without it, everything is on one line.
Handling Dates and Custom Types
Python’s json module doesn’t know how to serialize datetime objects by default. Use a custom encoder:
from datetime import datetime
import json
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
data = {"created_at": datetime.now()}
print(json.dumps(data, cls=DateEncoder))
Conclusion
The json module is essential for working with JSON in Python. Remember: loads/dumps for strings, load/dump for files. You’ll use this every time you consume an API, read a config, or build a backend service. Master these four functions and you’re set.
Read next: Building a REST API with Python and Flask
External resource: Python Docs — json module
Related Articles
CSS Flexbox in Plain English: A Beginner's Guide
Learn CSS Flexbox with simple, visual explanations. This guide covers display flex, justify-content, align-items, flex-wrap, and practical layouts every developer needs to know.
Docker for Backend Developers: A Practical Introduction
Learn how Docker works, why backend developers need it, and how to containerize your first Python or Go application in under 30 minutes.
Containerising a Backend Service: From Docker to Kubernetes
A practical walkthrough of containerising a Python backend service with Docker, deploying it to Kubernetes on ECS, and the production gaps that only show up once real traffic hits.