Learning

JSON File Operations

JSON File Operations

json.dumps() — Python → JSON String

python
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.loads() — JSON String → Python

python
json_str = '{"name": "Bob", "age": 25}' # Parse string to dict data = json.loads(json_str) print(type(data)) # <class 'dict'> print(data['name']) # 'Bob'

json.dump() — Python → JSON File

python
data = {'users': [{'id': 1, 'name': 'Alice'}]} with open('data.json', 'w') as f: json.dump(data, f, indent=2) # File now contains formatted JSON

json.load() — JSON File → Python

python
with open('data.json', 'r') as f: data = json.load(f) print(data['users'][0]['name']) # 'Alice'

Handling Non-Serializable Types

python
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)

Type Mapping Table

| 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!

Key Rules
  • •Use dump()/load() for files, dumps()/loads() for strings — the 's' stands for string
  • •Python's True/False/None become JSON's true/false/null — remember this when parsing!
  • •Tuples are converted to JSON arrays and come back as lists — convert manually if needed
  • •Always use indent=2 for readable JSON files, omit it for compact network payloads
  • •datetime, set, and custom class objects are NOT JSON serializable — use custom encoder or default function
Your Task

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.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should import json module
Should define save_config function
Should use json.dump with indent
Should define load_config function
Should handle FileNotFoundError
Should handle JSONDecodeError