
Python
Learn to read JSON files (common for APIs and configs) and write Python objects as JSON.
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"
# }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
# }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 | Python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number | int/float |
| true | True |
| false | False |
| null | None |
Ready to practice? Challenges | Quiz
Resources
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