import json
data = {
'name': 'Alice',
'age': 30,
'active': True,
'scores': [85, 90, 78],
'address': None
}
# Convert to JSON string
json_str = json.dumps(data)
print(json_str)
# {"name": "Alice", "age": 30, "active": true, "scores": [85, 90, 78], "address": null}
# Note the translations:
# Python True → JSON true
# Python False → JSON false
# Python None → JSON null
# Pretty print (indentation)
pretty = json.dumps(data, indent=2)
print(pretty)
# {
# "name": "Alice",
# "age": 30,
# ...
# }
# Sort keys
sorted_json = json.dumps(data, sort_keys=True, indent=2)json_str = '{"name": "Bob", "age": 25}'
# Parse string to dict
data = json.loads(json_str)
print(type(data)) # <class 'dict'>
print(data['name']) # 'Bob'data = {'users': [{'id': 1, 'name': 'Alice'}]}
with open('data.json', 'w') as f:
json.dump(data, f, indent=2)
# File now contains formatted JSONwith open('data.json', 'r') as f:
data = json.load(f)
print(data['users'][0]['name']) # 'Alice'from datetime import datetime
# This will FAIL!
# data = {'time': datetime.now()}
# json.dumps(data) # TypeError: Object of type datetime is not JSON serializable
# Solution 1: Custom encoder
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
json_str = json.dumps({'time': datetime.now()}, cls=DateTimeEncoder)
# Solution 2: Default function
def custom_serializer(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f'Type {type(obj)} not serializable')
json_str = json.dumps({'time': datetime.now()}, default=custom_serializer)| Python | JSON | |--------|------| | dict | object {} | | list, tuple | array [] | | str | string "" | | int, float | number | | True / False | true / false | | None | null |
Note: Tuples become JSON arrays. When loading back, they become lists!
Create a function `save_config(filepath, config_dict)` that writes a dictionary to a JSON file with indentation. Create a function `load_config(filepath)` that reads the JSON file and returns the dict. Wrap load_config in a try/except to handle FileNotFoundError and json.JSONDecodeError gracefully, returning an empty dict on failure.