|
Getting your Trinity Audio player ready...
|
Have you ever wondered how websites or apps share data with each other?
When your app fetches weather updates, login details, or product lists — it’s often using JSON behind the scenes.
JSON (JavaScript Object Notation) is one of the most popular data formats for storing and exchanging information, and Python makes it super easy to work with it using the JSON Module in Python.

In this article, you’ll learn:
- What JSON is
- How to read, write, and parse JSON data
- The difference between
loadvsloadsanddumpvsdumps - How to handle JSON files practically
- Real-life examples with complete explanations
Let’s dive in!
What is JSON?
JSON stands for JavaScript Object Notation, but don’t worry — it’s not limited to JavaScript.
It’s a lightweight data format that uses key-value pairs and arrays (lists) to represent data.
Here’s a simple example of JSON data:
{
"name": "Tejas",
"age": 25,
"skills": ["Python", "SQL", "Excel"],
"is_student": false
}
This looks similar to a Python dictionary, right?
That’s because JSON and Python data structures are very compatible — which is why converting between them is so easy!
Python’s json Module
Python’s built-in json module lets you:
- Convert JSON ↔ Python data types
- Read JSON data from files
- Write JSON data into files
- Handle APIs that return JSON responses
Let’s import it first:
import json
Converting Between JSON and Python
1. json.dumps() — Convert Python → JSON (as string)
json.dumps() turns a Python object into a JSON-formatted string.
import json
data = {
"name": "Ravi",
"age": 28,
"city": "Raipur",
"skills": ["Python", "Power BI"]
}
json_string = json.dumps(data)
print(json_string)
Output:
{"name": "Ravi", "age": 28, "city": "Raipur", "skills": ["Python", "Power BI"]}
Notice how it returns one long line — you can make it pretty using the indent parameter.
json_string = json.dumps(data, indent=4)
print(json_string)
Now your JSON looks beautiful and easy to read!
2. json.dump() — Write JSON to a File
If you want to save JSON data into a file, use json.dump():
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
This creates a file named data.json with properly formatted JSON.
3. json.loads() — Convert JSON String → Python Object
If you have a JSON string (from an API or file), use json.loads() to convert it back to Python.
json_data = '{"name": "Amit", "age": 30, "city": "Delhi"}'
python_data = json.loads(json_data)
print(python_data)
Output:
{'name': 'Amit', 'age': 30, 'city': 'Delhi'}
Now you can access data like a normal Python dictionary:
print(python_data["city"])
4. json.load() — Read JSON Data from File
When your data is already stored in a file, you can use json.load() directly:
with open("data.json", "r") as file:
data = json.load(file)
print(data["name"])
Difference Between dump/dumps and load/loads
| Function | Purpose | Works With |
|---|---|---|
dump() | Write JSON data to a file | File object |
dumps() | Convert Python object to string | Python object |
load() | Read JSON data from a file | File object |
loads() | Parse JSON data from a string | String |
👉Think of “s” in dumps/loads as “string”.
Supported Python Data Types
Here’s how Python and JSON data types match:
| Python Type | JSON Equivalent |
|---|---|
| dict | object |
| list, tuple | array |
| str | string |
| int, float | number |
| True | true |
| False | false |
| None | null |
Real-Life Example – Saving and Reading Student Data
Let’s create a Student Management mini program that saves student records in JSON format.
import json
students = [
{"name": "Ravi", "age": 21, "course": "BCA"},
{"name": "Asha", "age": 22, "course": "MBA"}
]
# Save to JSON file
with open("students.json", "w") as f:
json.dump(students, f, indent=4)
# Read from JSON file
with open("students.json", "r") as f:
data = json.load(f)
print("Student Records:")
for student in data:
print(f"{student['name']} - {student['course']}")
Output:
Student Records:
Ravi - BCA
Asha - MBA
Example: Nested JSON Handling
JSON data can be deeply nested, just like real-world data.
data = {
"employee": {
"name": "Tejas",
"department": "IT",
"projects": [
{"title": "SWS Portal", "status": "Completed"},
{"title": "Dashboard", "status": "Ongoing"}
]
}
}
# Convert to JSON string
json_data = json.dumps(data, indent=4)
print(json_data)
# Access nested elements
print(data["employee"]["projects"][0]["title"])
Output:
SWS Portal
Handling Non-Serializable Data
Not every Python object can be directly converted to JSON (like datetime objects).
Let’s see how to handle that.
import json
from datetime import datetime
data = {
"user": "Ravi",
"login_time": datetime.now()
}
# This will raise an error
# json.dumps(data)
# Fix: Convert datetime to string
data["login_time"] = data["login_time"].strftime("%Y-%m-%d %H:%M:%S")
json_data = json.dumps(data, indent=4)
print(json_data)
Error Handling in JSON
Working with files or user input? Always handle errors!
try:
with open("data.json", "r") as f:
data = json.load(f)
except FileNotFoundError:
print("File not found!")
except json.JSONDecodeError:
print("File is not a valid JSON!")
This ensures your program doesn’t crash even if the file is missing or corrupted.
Also Read: Error Handling in Python
Bonus: Using json.dump() and json.load() for Logs
You can use JSON to store logs or app data dynamically.
import json
def add_log(message):
try:
with open("logs.json", "r") as f:
logs = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
logs = []
from datetime import datetime
logs.append({"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "message": message})
with open("logs.json", "w") as f:
json.dump(logs, f, indent=4)
add_log("User logged in.")
add_log("Data exported successfully.")
Now every time the function runs, it appends a new log entry into logs.json.
Pro Tips
- Use
indent=4for readable JSON output. - Always validate JSON from user input using try-except.
- To reduce file size, use
separators=(",", ":")injson.dump(). - If you’re working with APIs — JSON will be your best friend!
Conclusion
JSON is everywhere — from APIs, web apps, data files, to logs.
Learning to handle JSON efficiently gives you a real-world edge as a Python developer.
What’s Next?
In the next post, we’ll learn about the OS Module in Python