Working with JSON in Python
JSON (JavaScript Object Notation) is a lightweight data format used everywhere in modern applications. Websites, APIs, databases, and mobile apps all exchange information using JSON because it is simple, readable, and universal.
Python comes with a built-in module called json that allows you to read, write, convert, and manipulate JSON data easily. Understanding JSON is essential for working with APIs, data pipelines, cloud services, and real-world applications.
What is JSON?
JSON stores data as key–value pairs, similar to Python dictionaries. It is language-independent, meaning any programming language can use it.
Example of JSON Data
{
"name": "Alex",
"age": 28,
"city": "New York",
"skills": ["Python", "SQL", "Data Analysis"]
}
In Python, this JSON object is equivalent to a dictionary. This makes JSON extremely easy to handle when building applications.
Importing the JSON Module
Python includes the json module by default.
We simply import it whenever we need to process JSON files or data.
import json
Converting JSON to Python (json.loads)
The function json.loads() converts JSON text into Python objects like dictionaries or lists.
This is often used when reading JSON data from APIs or web services.
Example: JSON String → Python Dictionary
json_data = '{"name": "Alex", "age": 28}'
python_obj = json.loads(json_data)
print(python_obj)
After conversion, you can access values just like any dictionary.
Converting Python to JSON (json.dumps)
The function json.dumps() converts Python objects back into JSON format.
It is useful when sending data to APIs or storing structured data in files.
Example: Dictionary → JSON String
data = {
"product": "Laptop",
"price": 1200,
"in_stock": True
}
json_text = json.dumps(data)
print(json_text)
Pretty Printing JSON
Pretty printing makes JSON easier to read with indentation and spacing. This is helpful when inspecting API responses or debugging.
json_text = json.dumps(data, indent=4)
print(json_text)
Reading JSON from a File (json.load)
To work with JSON stored in files, Python uses json.load().
This reads the entire file and converts it directly to a Python object.
Example: Reading from a File
with open("data.json", "r") as file:
content = json.load(file)
print(content)
Writing JSON to a File (json.dump)
To save Python data as a JSON file, we use json.dump().
This is useful when storing configuration files, logs, or structured datasets.
Example: Writing to a File
data = {
"id": 101,
"status": "active",
"role": "admin"
}
with open("output.json", "w") as file:
json.dump(data, file, indent=4)
Working with Nested JSON
JSON can contain objects inside other objects, creating a nested structure. Python handles nesting naturally using dictionaries and lists.
Example of Nested JSON
data = {
"employee": {
"name": "Michael",
"department": "IT",
"skills": ["Python", "Networking"]
}
}
print(data["employee"]["skills"])
Nested JSON is very common in APIs and real-world applications.
Handling JSON Errors
Invalid JSON can cause parsing errors. Python raises json.JSONDecodeError when the format is incorrect.
try:
result = json.loads("invalid JSON")
except json.JSONDecodeError:
print("Invalid JSON format!")
📝 Practice Exercises
Exercise 1
Convert a JSON string into a Python dictionary and print one key value.
Exercise 2
Create a Python dictionary and convert it into a formatted JSON string.
Exercise 3
Read a JSON file named info.json and print its contents.
Exercise 4
Write a Python dictionary into a JSON file named user.json.
✅ Practice Answers
Answer 1
text = '{"city": "London", "temperature": 18}'
result = json.loads(text)
print(result["city"])
Answer 2
data = {"brand": "Tesla", "model": "X"}
json_output = json.dumps(data, indent=4)
print(json_output)
Answer 3
with open("info.json", "r") as f:
content = json.load(f)
print(content)
Answer 4
user = {"username": "admin", "access": "full"}
with open("user.json", "w") as f:
json.dump(user, f, indent=4)