
Working with JSON Data: Python and Web Standards
In the previous lesson, you learned how to store spreadsheet-style tables in CSV files. CSV works great when every row has the exact same columns. However, modern apps often need to save nested data, such as user preferences, a list of recent files, or data returned from a website.
This is where JSON comes in. In this lesson, you will learn how JSON maps to Python dictionaries and lists, how to read and write JSON using Python’s built-in json module, and how to build an Application Settings and State Manager that remembers user preferences safely.
1. What Is JSON and Why Does It Dominate Web Data?
JSON stands for JavaScript Object Notation. Even though its name mentions JavaScript, JSON is a plain text format that almost every programming language can read and write. Websites, mobile apps, and cloud APIs use JSON to send structured data over the internet.
If you have already used Python dictionaries and lists, JSON will look very familiar. Here is an example of a JSON file:
{
"app_name": "Notes Pro",
"theme": "dark",
"font_size": 14,
"auto_save": true,
"recent_files": ["notes.txt", "todo.txt"],
"last_backup": null
}
Look closely at the syntax. JSON uses double quotes for all keys and strings, lowercase true and false for booleans, and null for an empty value.
2. How Python Types Map to JSON
Python’s built-in json module automatically converts between Python data types and JSON text. Here is how the main types match up:
- Python
dictbecomes a JSON object ({}). - Python
listortuplebecomes a JSON array ([]). - Python
strbecomes a JSON string ("text"). - Python
intandfloatbecome JSON numbers. - Python
TrueandFalsebecometrueandfalse. - Python
Nonebecomesnull.
3. Working with JSON Strings: json.dumps() and json.loads()
When you want to convert Python data into a JSON string in memory (or turn a JSON string back into Python data), use json.dumps() (“dump string”) and json.loads() (“load string”).
import json
user_profile: dict[str, str | int | bool | list[str]] = {
"username": "rey",
"level": 3,
"is_active": True,
"badges": ["phase-1", "csv-pro"],
}
# Convert Python dict to a formatted JSON string
json_text = json.dumps(user_profile, indent=4)
print(json_text)
# Convert JSON string back into a Python dict
parsed_data = json.loads(json_text)
print(parsed_data["username"])
print(type(parsed_data))
Passing indent=4 makes the JSON output clean and easy for humans to read. Without indent, Python writes everything on one long line.
4. Reading and Writing JSON Files: json.dump() and json.load()
Notice the difference in the function names: dumps and loads end with an s for strings, while dump and load (without the s) work directly with files.
import json
from pathlib import Path
config_path = Path("config.json")
config_data = {"theme": "dark", "font_size": 16}
# Write Python data directly to a JSON file
with open(config_path, "w", encoding="utf-8") as file:
json.dump(config_data, file, indent=4)
# Read JSON file back into a Python dictionary
with open(config_path, "r", encoding="utf-8") as file:
loaded_config = json.load(file)
print(loaded_config["theme"])
Always pass encoding="utf-8" when opening JSON files so international characters (such as accented letters or emoji) save and load properly on every operating system.
5. Practical Project: Application Settings and State Manager
Let’s put this into practice by building an Application Settings and State Manager in a file named settings_manager.py. It loads saved settings from app_settings.json, handles missing or corrupted files safely using try and except json.JSONDecodeError, and lets the user update preferences or reset to defaults.
At the bottom of the script, if __name__ == "__main__": is a standard Python guard that runs main() only when you execute this file directly (we will cover how that works in Lesson 15).
import json
from pathlib import Path
SETTINGS_FILE = Path("app_settings.json")
def get_default_settings() -> dict[str, str | int | bool | list[str]]:
"""Return a fresh copy of the default application settings."""
return {
"username": "Guest",
"theme": "light",
"font_size": 14,
"auto_save": True,
"recent_files": [],
}
def load_settings(file_path: Path) -> dict[str, str | int | bool | list[str]]:
"""Load settings from JSON, falling back to defaults if missing or invalid."""
if not file_path.exists():
return get_default_settings()
try:
content = file_path.read_text(encoding="utf-8").strip()
if not content:
print("Settings file was empty. Loading defaults.")
return get_default_settings()
data = json.loads(content)
if not isinstance(data, dict):
print("Invalid settings format. Loading defaults.")
return get_default_settings()
return data
except json.JSONDecodeError:
print("Settings file is corrupted. Loading default settings.")
return get_default_settings()
def save_settings(
file_path: Path,
settings: dict[str, str | int | bool | list[str]],
) -> None:
"""Save settings dictionary to a formatted JSON file."""
with open(file_path, "w", encoding="utf-8") as file:
json.dump(settings, file, indent=4)
def show_settings(settings: dict[str, str | int | bool | list[str]]) -> None:
"""Print the current settings in a readable format."""
print("\n--- Current Settings ---")
for key, value in settings.items():
print(f"{key}: {value}")
def get_valid_font_size(prompt: str) -> int:
"""Prompt the user until they enter a valid font size between 8 and 48."""
while True:
try:
size = int(input(prompt))
if 8 <= size <= 48:
return size
print("Please enter a font size between 8 and 48.")
except ValueError:
print("Invalid input. Please enter a whole number.")
def main() -> None:
"""Run the Application Settings and State Manager CLI."""
settings = load_settings(SETTINGS_FILE)
print("Welcome to the Application Settings Manager!")
while True:
print("\nMenu:")
print("1. View Current Settings")
print("2. Update Username & Theme")
print("3. Change Font Size")
print("4. Toggle Auto-Save")
print("5. Reset to Default Settings")
print("6. Save and Exit")
choice = input("Choose an option (1-6): ").strip()
if choice == "1":
show_settings(settings)
elif choice == "2":
username = input("Enter username: ").strip()
if username:
settings["username"] = username
theme = input("Choose theme (light/dark): ").strip().lower()
if theme in ("light", "dark"):
settings["theme"] = theme
else:
print("Unknown theme. Keeping previous theme.")
save_settings(SETTINGS_FILE, settings)
print("Preferences updated.")
elif choice == "3":
settings["font_size"] = get_valid_font_size("Enter font size (8-48): ")
save_settings(SETTINGS_FILE, settings)
print("Font size updated.")
elif choice == "4":
current = bool(settings.get("auto_save", True))
settings["auto_save"] = not current
save_settings(SETTINGS_FILE, settings)
print(f"Auto-save is now: {settings['auto_save']}")
elif choice == "5":
settings = get_default_settings()
save_settings(SETTINGS_FILE, settings)
print("Settings reset to defaults.")
elif choice == "6":
save_settings(SETTINGS_FILE, settings)
print("Settings saved to app_settings.json. Goodbye!")
break
else:
print("Invalid choice. Please enter a number from 1 to 6.")
if __name__ == "__main__":
main()
Run python settings_manager.py from your terminal, change your theme and font size, and exit. Open app_settings.json in your editor to see the clean JSON file Python created for you.
Common Beginner Mistakes
- Mixing up
json.load()andjson.loads(): Remember that thesstands for string. Passing a file path or file object tojson.loads()raises aTypeError. - Using single quotes or trailing commas in JSON: Python allows single quotes and trailing commas in dictionaries, but valid JSON requires double quotes (
"key") and forbids trailing commas after the last item. - Not handling empty or broken JSON files: Calling
json.loads("")on an empty file raises ajson.JSONDecodeError. Always check for empty content and wrap parsing intryandexcept json.JSONDecodeError. - Trying to save unsupported Python types: Objects like
Pathorsetcannot be saved directly to JSON and raise aTypeError. Convert them tostrorlistfirst.
Try It Yourself
- Recent Files Tracker (
recent_files.py): Add a menu option that lets the user record a recently opened filename intosettings["recent_files"], keeping only the last 5 filenames. - Corrupted File Test (
test_bad_json.py): Openapp_settings.jsonin a text editor, delete the closing}, and run your program to verify thatload_settings()recovers cleanly with defaults. - JSON Key Sorter (
sorted_config.py): Updatejson.dump()to includesort_keys=Trueand observe how the keys inapp_settings.jsonare organized alphabetically.
Frequently Asked Questions
When should I use JSON instead of CSV?
Use CSV for flat, table-like data where every row shares the same columns (like spreadsheets or expense logs). Use JSON for nested structures, configuration files, or data exchanged with web APIs.
Why did json.load() convert my JSON true to Python True?
JSON uses lowercase true, false, and null, while Python uses True, False, and None. The json module translates these values automatically in both directions.
Can a JSON file have comments like # in Python?
No. Standard JSON does not support comments. Adding # or // lines inside a .json file will trigger a json.JSONDecodeError when Python tries to read it.
What happens if I save a Python Path object inside a JSON dictionary?
Python raises TypeError: Object of type Path is not JSON serializable. Convert any Path object to a string with str(my_path) before calling json.dump().
Need to revisit tabular files first? Check out the previous lesson: Working with CSV Files: Tabular Data in Python. In our next article, Python Modules and Standard Library Highlights, you will explore Python’s built-in toolkit, including math, random, datetime, and sys.
Learning programming works best as a collaborative process, and your questions and insights help make these tutorials more effective for everyone. If you run into a JSONDecodeError, get confused between load() and loads(), or add a cool feature to the settings manager, please share your experience in the comments. Your feedback helps create a learning community where we can all benefit from each other’s discoveries and solutions.
You Might Also Like

Working with CSV Files: Tabular Data in Python
Learn to read, write, and format CSV files in Python using csv.reader, csv.DictReader, and...

Phase 1 Capstone: Building a Command-Line Inventory System
Build a complete Python command-line inventory system combining dictionaries, lists, funct...

A Week After PHP2Shell: This Is What I Learned
A personal story about discovering vulnerable PHP on my own servers after the PHP2Shell ne...

Working with Files in Python: Text Persistence with Pathlib
Learn how to save and load data permanently in Python using the modern pathlib module, con...
Comments
Loading comments…