Working with JSON
JSON (JavaScript Object Notation) is a popular data format.
Reading JSON
import json # Read from file with open('data.json', 'r') as file: data = json.load(file) print(data) # Parse JSON string json_string = '{"name": "Alice", "age": 25}' data = json.loads(json_string)
Writing JSON
import json data = { "name": "Alice", "age": 25, "hobbies": ["reading", "coding"] } # Write to file (pretty formatted) with open('output.json', 'w') as file: json.dump(data, file, indent=4) # Convert to string json_string = json.dumps(data, indent=2)
Nested JSON
data = { "users": [ {"name": "Alice", "age": 25}, {"name": "Bob", "age": 30} ], "total": 2 } # Access nested data first_user = data["users"][0] print(first_user["name"])
JSON vs Dictionary
# Python dict → JSON python_dict = {"name": "Alice", "active": True} json_string = json.dumps(python_dict) # JSON → Python dict json_string = '{"name": "Bob", "age": 30}' python_dict = json.loads(json_string)
Practice Exercises
- Read and parse JSON file
- Write dictionary to JSON
- Update JSON file
- Convert CSV to JSON
- Work with nested JSON data
Next Lesson: Exception Handling