Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
📖 File Fundamentals📖 Reading Files Effectively✍️ Writing Files Correctly🗂️ Working with File Paths🤝 Context Managers & Safety📊 CSV Data Processing🔄 JSON Parsing & Serialization🔐 Binary Files & Encoding⚙️ Performance & Best Practices
Python/File Io/Json Parsing

🔄 JSON Parsing & Serialization — Data Interchange Format

Learn to read JSON files (common for APIs and configs) and write Python objects as JSON.


🎯 Reading JSON Files

Use `json.load()` to parse JSON data.

import json

# Read JSON file
with open("config.json", "r") as file:
    data = json.load(file)

print(data)  # Python dictionary
print(data["host"])  # Access like dictionary

# File contents (config.json):
# {
#   "host": "localhost",
#   "port": 5432,
#   "database": "myapp"
# }

💡 Writing JSON Files

Use `json.dump()` to save Python objects as JSON.

import json

# Python dictionary
config = {
    "host": "localhost",
    "port": 5432,
    "database": "myapp",
    "debug": True
}

# Write to JSON file
with open("config.json", "w") as file:
    json.dump(config, file, indent=2)  # indent for readability

# File will contain:
# {
#   "host": "localhost",
#   "port": 5432,
#   "database": "myapp",
#   "debug": true
# }

🎨 Real-World Example: Working with API Responses

import json

# Simulating API response saved to file
api_response = {
    "status": "success",
    "users": [
        {"id": 1, "name": "Alice", "email": "alice@example.com"},
        {"id": 2, "name": "Bob", "email": "bob@example.com"}
    ]
}

# Save response
with open("users.json", "w") as file:
    json.dump(api_response, file, indent=2)

# Later, read and process
with open("users.json", "r") as file:
    data = json.load(file)

for user in data["users"]:
    print(f"{user['name']}: {user['email']}")

📊 JSON vs Python Data Types

JSONPython
objectdict
arraylist
stringstr
numberint/float
trueTrue
falseFalse
nullNone

🔑 Key Takeaways

  • ✅ `json.load()` reads JSON file
  • ✅ `json.dump()` writes JSON file
  • ✅ JSON is human-readable text format
  • ✅ Perfect for APIs and configurations
  • ✅ Use `indent=2` for pretty formatting

Ready to practice? Challenges | Quiz


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn