Working with JSON
Introduction to JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format. It's commonly used for storing and exchanging data between applications. Python's json module makes it easy to work with JSON data.
JSON is human-readable, language-independent, and perfect for configuration files, APIs, and data storage.
JSON Structure
JSON data looks similar to Python dictionaries and lists:
json_structure.py
# JSON example
json_data = """
{
"name": "Alice",
"age": 25,
"city": "New York",
"hobbies": ["reading", "coding"]
}
"""
# JSON supports:
# - Objects (dictionaries): {}
# - Arrays (lists): []
# - Strings: "text"
# - Numbers: 123, 45.6
# - Booleans: true, false
# - null: null
Reading JSON
Use json.loads() to parse JSON strings, or json.load() to read from files:
reading_json.py
import json
# Parse JSON string
json_string = '{"name": "Alice", "age": 25}'
data = json.loads(json_string)
print(data["name"]) # Alice
print(data["age"]) # 25
# Read from file
with open("data.json", "r") as file:
data = json.load(file)
print(data)
# JSON becomes Python dict/list
print(type(data)) # <class 'dict'>
Writing JSON
Use json.dumps() to convert Python objects to JSON strings, or json.dump() to write to files:
writing_json.py
import json
# Convert Python dict to JSON string
data = {
"name": "Alice",
"age": 25,
"city": "New York"
}
json_string = json.dumps(data)
print(json_string) # {"name": "Alice", "age": 25, "city": "New York"}
# Pretty print with indentation
pretty_json = json.dumps(data, indent=2)
print(pretty_json)
# Write to file
with open("output.json", "w") as file:
json.dump(data, file, indent=2)
Common Use Cases
JSON is commonly used for:
- API responses and requests
- Configuration files
- Data storage and exchange
- Web applications
- Mobile app data
Best Practices
✅ JSON Tips
• Use indent parameter for readable output
• Handle JSON decode errors when reading
• Validate JSON structure before processing
• Use ensure_ascii=False for non-ASCII characters
main.py
📤 Output
Click "Run" to execute...