1. Parsing JSON Strings in Python (`json.loads`)
To convert a JSON string into a native Python dictionary or list, use `json.loads()` ("load string"). Python automatically converts JSON numbers to `int`/`float`, JSON booleans to `bool`, and JSON `null` to `None`.
import json
json_string = '{"name": "Alice", "role": "admin", "active": true, "score": null}'
# Parse JSON string into Python dictionary
data = json.loads(json_string)
print(type(data)) # <class 'dict'>
print(data["name"]) # Alice
print(data["active"]) # True (converted to Python bool)
print(data["score"]) # None (converted to Python None)Explanation: `json.loads()` converts valid JSON strings into Python data types automatically.
Pro Tips
- Use `json.load(file_object)` when reading directly from a `.json` file on disk.
- Always wrap `json.loads()` in a `try-except json.JSONDecodeError` block to handle invalid JSON syntax safely.
2. Pretty Printing JSON in Python (`json.dumps`)
To format a Python dictionary into a human-readable, indented JSON string, pass `indent=2` or `indent=4` to `json.dumps()` ("dump string"). Use `sort_keys=True` to order keys alphabetically.
import json
user_data = {
"id": 101,
"username": "dev_expert",
"permissions": ["read", "write", "execute"],
"settings": {"theme": "dark", "notifications": True}
}
# Pretty print JSON string with 2 spaces and sorted keys
pretty_json = json.dumps(user_data, indent=2, sort_keys=True)
print(pretty_json)Explanation: `json.dumps(obj, indent=2)` turns a Python dictionary into a formatted JSON string.
Pro Tips
- Set `separators=(",", ": ")` to remove trailing spaces after colons for cleaner logs.
- For minified JSON output in Python, set `separators=(",", ":")` with zero indent.
3. Handling Python `datetime` Serialization Errors
Python's built-in `json.dumps()` raises a `TypeError: Object of type datetime is not serializable` when trying to serialize `datetime` objects directly. Pass a custom `default` converter function to resolve this.
import json
from datetime import datetime
payload = {
"event": "user_login",
"timestamp": datetime.now()
}
# Custom serializer for non-standard objects
def json_serializer(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Type {type(obj)} not serializable")
# Dump JSON using custom default handler
json_output = json.dumps(payload, default=json_serializer, indent=2)
print(json_output)Explanation: Passing `default=json_serializer` allows Python to convert custom objects like `datetime` into ISO 8601 strings.