Python JSON
Learn to work with JSON data in simple steps
š What is JSON?
JSON (JavaScript Object Notation) is like a universal language for sharing data between programs. Think of it as a way to organize information that both humans and computers can easily read and understand.
import json
# A simple JSON example
person_info = '{"name": "Alice", "age": 25, "city": "New York"}'
# Convert JSON to Python dictionary
person = json.loads(person_info)
print(person["name"]) # Prints: Alice
What is JSON?
Text-Based Format
Human-readable data format
Web APIs
Standard format for REST APIs
Data Exchange
Perfect for client-server communication
Python Integration
Built-in json module support
Lesson 1: What Does JSON Look Like?
JSON looks very similar to Python dictionaries, but it's stored as text:
# Python dictionary (what we know)
student = {
"name": "Bob",
"age": 20,
"subjects": ["Math", "Science"],
"graduated": False
}
print("Python dictionary:", student)
print("Type:", type(student))
# JSON string (text format)
json_string = '{"name": "Bob", "age": 20, "subjects": ["Math", "Science"], "graduated": false}'
print("\nJSON string:", json_string)
print("Type:", type(json_string))
-
JSON uses
"double quotes"for strings -
JSON uses
true/false(lowercase) for booleans - JSON is always text/string format
Lesson 2: Reading JSON Data
Use
json.loads()
to convert JSON text into Python objects:
import json
# JSON string with weather data
weather_json = '''
{
"city": "London",
"temperature": 18,
"condition": "Cloudy",
"humidity": 65,
"is_raining": false
}
'''
# Convert JSON to Python dictionary
weather = json.loads(weather_json)
# Now we can use it like a normal dictionary
print(f"City: {weather['city']}")
print(f"Temperature: {weather['temperature']}°C")
print(f"Condition: {weather['condition']}")
if weather['is_raining']:
print("Don't forget your umbrella!")
else:
print("No rain expected!")
# JSON with a list of students
students_json = '''
[
{"name": "Alice", "grade": 85},
{"name": "Bob", "grade": 92},
{"name": "Charlie", "grade": 78}
]
'''
# Convert to Python list
students = json.loads(students_json)
print("Class Grades:")
for student in students:
name = student["name"]
grade = student["grade"]
print(f"{name}: {grade}%")
Lesson 3: Creating JSON Data
Use
json.dumps()
to convert Python objects into JSON text:
import json
# Create a Python dictionary
my_profile = {
"username": "coder123",
"email": "coder@example.com",
"age": 22,
"hobbies": ["coding", "gaming", "reading"],
"is_student": True
}
# Convert to JSON string
profile_json = json.dumps(my_profile)
print("Python dictionary:")
print(my_profile)
print("\nJSON string:")
print(profile_json)
# Make JSON easier to read with indentation
book_info = {
"title": "Python for Beginners",
"author": "Jane Smith",
"pages": 250,
"chapters": ["Introduction", "Variables", "Functions", "Classes"]
}
# Pretty JSON with indentation
pretty_json = json.dumps(book_info, indent=4)
print("Pretty formatted JSON:")
print(pretty_json)
Lesson 4: Saving and Loading JSON Files
You can save JSON data to files and load it back later:
import json
# Create some data to save
my_favorites = {
"movies": ["The Matrix", "Inception", "Interstellar"],
"books": ["1984", "To Kill a Mockingbird"],
"colors": ["blue", "green", "purple"],
"number": 42
}
# Save to a JSON file
with open("my_favorites.json", "w") as file:
json.dump(my_favorites, file, indent=4)
print("ā
Data saved to my_favorites.json!")
import json
# Load data from JSON file
try:
with open("my_favorites.json", "r") as file:
loaded_favorites = json.load(file)
print("ā
Data loaded successfully!")
print("\nYour favorite movies:")
for movie in loaded_favorites["movies"]:
print(f" š¬ {movie}")
print(f"\nYour lucky number: {loaded_favorites['number']}")
except FileNotFoundError:
print("ā File not found. Make sure to save data first!")
Lesson 5: Building a Simple Contact Book
Let's create a contact book that saves data in JSON format:
import json
import os
class SimpleContactBook:
def __init__(self):
self.filename = "contacts.json"
self.contacts = self.load_contacts()
def load_contacts(self):
"""Load contacts from JSON file"""
if os.path.exists(self.filename):
try:
with open(self.filename, "r") as file:
return json.load(file)
except:
print("ā ļø Error loading contacts. Starting fresh.")
return []
return []
def save_contacts(self):
"""Save contacts to JSON file"""
try:
with open(self.filename, "w") as file:
json.dump(self.contacts, file, indent=4)
print("ā
Contacts saved!")
return True
except:
print("ā Error saving contacts!")
return False
def add_contact(self, name, phone, email=""):
"""Add a new contact"""
contact = {
"name": name,
"phone": phone,
"email": email
}
self.contacts.append(contact)
self.save_contacts()
print(f"ā
Added {name} to contacts!")
def show_all_contacts(self):
"""Display all contacts"""
if not self.contacts:
print("š No contacts found!")
return
print(f"\nš Your Contacts ({len(self.contacts)} total):")
print("-" * 40)
for i, contact in enumerate(self.contacts, 1):
print(f"{i}. {contact['name']}")
print(f" š± {contact['phone']}")
if contact['email']:
print(f" š§ {contact['email']}")
print()
def find_contact(self, name):
"""Find a contact by name"""
for contact in self.contacts:
if name.lower() in contact['name'].lower():
return contact
return None
# Demo the contact book
def demo_contact_book():
book = SimpleContactBook()
print("š Simple Contact Book Demo")
print("=" * 30)
# Add some sample contacts
book.add_contact("Alice Johnson", "555-0123", "alice@email.com")
book.add_contact("Bob Smith", "555-0456")
book.add_contact("Charlie Brown", "555-0789", "charlie@email.com")
# Show all contacts
book.show_all_contacts()
# Find a specific contact
found = book.find_contact("Alice")
if found:
print(f"š Found: {found['name']} - {found['phone']}")
# Run the demo
demo_contact_book()
Quick Reference: JSON Methods
json.loads()
Convert JSON string to Python object
# JSON string ā Python
data = json.loads('{"name": "Alice"}')
print(data["name"]) # Alice
json.dumps()
Convert Python object to JSON string
# Python ā JSON string
data = {"name": "Alice"}
json_str = json.dumps(data)
print(json_str) # {"name": "Alice"}
json.load()
Read JSON from a file
# Read from file
with open("data.json", "r") as f:
data = json.load(f)
json.dump()
Write JSON to a file
# Write to file
with open("data.json", "w") as f:
json.dump(data, f, indent=4)
Common JSON Errors and Solutions
š« JSONDecodeError
Problem: Invalid JSON format
# Wrong: Single quotes
bad_json = "{'name': 'Alice'}"
# Right: Double quotes
good_json = '{"name": "Alice"}'
# Always use try-except for safety
try:
data = json.loads(json_string)
except json.JSONDecodeError:
print("Invalid JSON format!")
š« File Not Found
Problem: JSON file doesn't exist
# Check if file exists first
import os
if os.path.exists("data.json"):
with open("data.json", "r") as f:
data = json.load(f)
else:
print("File not found!")
š« KeyError
Problem: Trying to access a key that doesn't exist
# Use .get() method for safety
data = {"name": "Alice"}
# Wrong: Might cause KeyError
# age = data["age"]
# Right: Safe with default value
age = data.get("age", "Unknown")
print(f"Age: {age}")