Working with JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format. Python's `json` module provides functions to parse JSON strings and convert Python objects to JSON. It's commonly used for APIs and configuration files.
Converting Python to JSON (Serialization)
Use `json.dumps()` to convert a Python object to a JSON string. Use `json.dump()` to write directly to a file.
import json
data = {
"name": "Alice",
"age": 30,
"city": "New York"
}
json_string = json.dumps(data, indent=2)
print(json_string)
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
Converting JSON to Python (Deserialization)
Use `json.loads()` to parse a JSON string, or `json.load()` to read from a file.
json_string = '{"name": "Bob", "age": 25}'
parsed = json.loads(json_string)
print(parsed["name"]) # Bob
with open("data.json", "r") as f:
loaded = json.load(f)
Commonly Used Options
- `indent` – pretty print with indentation.
- `sort_keys` – sort keys alphabetically.
- `ensure_ascii=False` – allow non‑ASCII characters.
Two Minute Drill
- JSON is a popular data interchange format.
- Use `json.dumps()` to convert Python objects to JSON strings; `json.loads()` for the reverse.
- Use `json.dump()` and `json.load()` to work directly with files.
- Common options: `indent`, `sort_keys`, `ensure_ascii`.
Need more clarification?
Drop us an email at career@quipoinfotech.com
