Welcome to Day 45 of the 100 Days of Python series!
Today, we’ll explore how to work with JSON (JavaScript Object Notation) in Python — a common data format used in APIs, configuration files, and data exchange between systems.
1. What is JSON?
- JSON is a lightweight data-interchange format.
- It is human-readable and language-independent.
- It uses a key-value pair structure similar to Python dictionaries.
Example JSON:
{
"name": "Alice",
"age": 25,
"skills": ["Python", "Data Science"]
}
2. Python’s json
Module
Python provides a built-in json
module to:
- Parse JSON into Python objects.
- Convert Python objects into JSON strings.
import json
3. Reading JSON (Deserialization)
To read JSON from a file and convert it into a Python object:
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)
print(type(data)) # dict
Key Method:
-
json.load(file)
→ Reads JSON from a file and converts it to a Python object.
4. Writing JSON (Serialization)
To write Python objects to a JSON file:
data = {
"name": "Alice",
"age": 25,
"skills": ["Python", "Data Science"]
}
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
Key Method:
-
json.dump(obj, file, indent=4)
→ Writes Python objects to a file in JSON format. -
indent
makes it human-readable.
5. Converting JSON Strings
Sometimes you work with JSON from APIs, which comes as a string.
String to Python Object:
json_string = '{"name": "Bob", "age": 30}'
data = json.loads(json_string)
print(data["name"]) # Bob
Python Object to JSON String:
data = {"name": "Charlie", "age": 22}
json_str = json.dumps(data, indent=2)
print(json_str)
6. Common Pitfalls
- JSON keys must be strings.
- JSON cannot store Python-specific objects like sets or functions directly.
- Use
default=str
when serializing objects likedatetime
.
7. Mini Example
import json
user = {
"username": "tech_guru",
"active": True,
"followers": 1050
}
# Save to file
with open("user.json", "w") as f:
json.dump(user, f, indent=4)
# Read from file
with open("user.json", "r") as f:
loaded_user = json.load(f)
print(loaded_user)
Notes
-
Serialization = Python → JSON (
dump
,dumps
) -
Deserialization = JSON → Python (
load
,loads
) - Always handle file operations with
with
to ensure proper closure.
Challenge
Create a Python program that:
- Reads user details (name, age, skills) from
input()
. - Saves them to a JSON file.
- Reads the file and prints the stored details.
Top comments (0)