Question №33
Remaining:
How to work with JSON in Python?
Sample Answer
Show Answer by Default
JSON (JavaScript Object Notation) is a text-based format for data exchange. Python provides a built-in json module for working with it.
Main functions:
- json.dumps() — Python object → JSON string
- json.loads() — JSON string → Python object
- json.dump() — Python object → JSON file
- json.load() — JSON file → Python object
Serialization (Python → JSON):
import json data = { "name": "Anna", "age": 25, "hobbies": ["reading", "swimming"], "active": True } # To a string json_string = json.dumps(data, ensure_ascii=False, indent=2) print(json_string) # To a file with open("data.json", "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2)
Deserialization (JSON → Python):
# From a string json_string = '{"name": "Anna", "age": 25}' data = json.loads(json_string) print(data["name"]) # Anna # From a file with open("data.json", "r", encoding="utf-8") as f: data = json.load(f)
