Goal: Learn to save and load data in JSON format.
What Is JSON?
JSON (JavaScript Object Notation) is a text format for storing data. It looks like a Python dictionary, is human-readable, and is supported by every programming language.
{
"name": "Alice",
"age": 25,
"balance": 1000.50,
"transactions": ["deposit", "withdraw"]
}
Python to JSON type mapping
| Python | JSON |
|---|---|
dict |
Object {} |
list |
Array [] |
str |
String "text" |
int, float |
Number 42, 3.14 |
True, False |
true, false |
None |
null |
Core functions of the json module
import json
# json.dump() — save to a file
# json.load() — load from a file
# json.dumps() — convert to a string
# json.loads() — parse from a string
Saving: json.dump()
import json
user = {
"name": "Alice",
"age": 25,
"balance": 1000
}
with open("user.json", "w", encoding="utf-8") as file:
json.dump(user, file, indent=4, ensure_ascii=False)
Parameters:
- indent=4 — indentation for readability
- ensure_ascii=False — preserves non-ASCII characters
Result in user.json:
{
"name": "Alice",
"age": 25,
"balance": 1000
}
Loading: json.load()
import json
with open("user.json", "r", encoding="utf-8") as file:
user = json.load(file)
print(user["name"]) # Alice
print(user["balance"]) # 1000
Safe Loading with try/except
The file may not exist or may be corrupted — always wrap your load call:
import json
try:
with open("user.json", "r", encoding="utf-8") as file:
user = json.load(file)
print("Data loaded!")
except FileNotFoundError:
print("File not found, creating a new profile.")
user = {"name": "Stranger", "age": 0, "balance": 0}
except json.JSONDecodeError:
print("File is corrupted, using defaults.")
user = {"name": "Stranger", "age": 0, "balance": 0}
Practical Example: BankAccount
import json
class BankAccount:
def __init__(self, name, balance=0):
self.name = name
self.balance = balance
self.transactions = []
def deposit(self, amount):
self.balance += amount
self.transactions.append(f"Deposit: +{amount}")
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds!")
return
self.balance -= amount
self.transactions.append(f"Withdrawal: -{amount}")
def save(self, filename):
data = {
"name": self.name,
"balance": self.balance,
"transactions": self.transactions
}
with open(filename, "w", encoding="utf-8") as file:
json.dump(data, file, indent=4, ensure_ascii=False)
@staticmethod
def load(filename):
try:
with open(filename, "r", encoding="utf-8") as file:
data = json.load(file)
account = BankAccount(data["name"], data["balance"])
account.transactions = data["transactions"]
return account
except FileNotFoundError:
print("File not found!")
return None
# Usage
account = BankAccount("Alice", 1000)
account.deposit(500)
account.withdraw(200)
account.save("alice.json")
loaded = BankAccount.load("alice.json")
print(f"Balance: {loaded.balance}")
print(f"History: {loaded.transactions}")
Contents of alice.json:
{
"name": "Alice",
"balance": 1300,
"transactions": [
"Deposit: +500",
"Withdrawal: -200"
]
}
json.dumps() and json.loads() — Working with Strings
import json
# dumps() — dict → string (for APIs, networking, logging)
data = {"name": "Alice", "age": 25}
json_string = json.dumps(data, ensure_ascii=False)
print(json_string) # {"name": "Alice", "age": 25}
print(type(json_string)) # <class 'str'>
# loads() — string → dict (when receiving data from an API)
raw = '{"name": "Bob", "balance": 500}'
parsed = json.loads(raw)
print(parsed["name"]) # Bob
print(type(parsed)) # <class 'dict'>
What Cannot Be Saved to JSON
# Functions → TypeError
data = {"func": print}
json.dump(data, file) # ❌ TypeError
# Class instances → TypeError
user = User("Alice")
json.dump(user, file) # ❌ TypeError
# Fix: convert to a dictionary
json.dump({"name": user.name}, file) # ✅
# Sets → TypeError
data = {"numbers": {1, 2, 3}}
json.dump(data, file) # ❌ TypeError
# Fix: convert to a list
data = {"numbers": list({1, 2, 3})} # ✅
Pattern: Config File
import json
def load_config(filename="config.json"):
try:
with open(filename, "r", encoding="utf-8") as file:
return json.load(file)
except FileNotFoundError:
return {
"app_name": "MyApp",
"version": "1.0",
"debug": False,
"max_accounts": 10
}
config = load_config()
print(f"App: {config['app_name']} v{config['version']}")
Common Mistakes
1. Forgot ensure_ascii=False:
# ❌ Non-ASCII chars become \uXXXX escape sequences
json.dump(data, file)
# ✅ Correct
json.dump(data, file, ensure_ascii=False)
2. Tried to serialize a class instance directly:
# ❌ TypeError
json.dump(my_object, file)
# ✅ Convert to a dict first
json.dump(my_object.__dict__, file)
Summary
json.dump(data, file, indent=4, ensure_ascii=False)— save to a filejson.load(file)— load from a filejson.dumps(data)— convert to a stringjson.loads(string)— parse from a string- Always use
try/exceptwhen loading - Serialize class instances as dictionaries
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!