Working with JSON files/shaare/TU-K-w
Working with JSON files
- JSON is the standard format for data exchange in web services and cloud APIs.
- Python’s built-in
jsonmodule provides functions to convert between JSON text and Python objects. - Key operations: parsing JSON from strings/files and serializing Python objects to JSON strings/files.
JSON Syntax and Python Mapping
- JSON objects (
{}) map to Pythondict. - JSON arrays (
[]) map to Pythonlist. - JSON strings map to Python
str, numbers tointorfloat. true/false→True/False;null→None.- Keys in JSON objects must be double-quoted strings; no trailing commas.
Deserializing JSON
- Use
json.loads()to parse JSON strings into Python objects. - Raises
json.JSONDecodeErroron invalid JSON. - Common in DevOps for handling API response bodies.
import json
api_response_str = '{"status": "active", "instance_id": "i-12345", "cores": 4, "tags": ["web", "prod"]}'
try:
data = json.loads(api_response_str)
print(f"Parsed data type: {type(data)}")
print(f"Instance ID: {data.get("instance_id", None)}")
print(f"Tags: {data.get("tags", None)}")
except json.JSONDecodeError as e:
print(f"Failed to parse JSON: {e}")
Parsing JSON Files
- Use
json.load()to read JSON from an open file object. - Always open files with
encoding='utf-8'when dealing with JSON. - Wrap file operations in
withto ensure proper closure.
import json
from pathlib import Path
config_path = Path("service_config.json")
with config_path.open("r", encoding="utf-8") as file:
config_data = json.load(file)
for config in config_data:
service_name = config.get("service", None)
if service_name:
print(f"Service: {service_name}")
print(f"Enabled: {config.get("enabled", False)}")
print('-' * 20)
Example of service_config.json
[
{
"service": "database",
"port": 5432,
"connection_pool": 10,
"enabled": true
},
{
"service": "cache",
"port": 6379,
"connection_pool": 5
},
{
"service": "api",
"port": 8080,
"connection_pool": 3,
"enabled": true
},
{
"port": 5000,
"connection_pool": 3,
"enabled": true
}
]
Serializing Python objects to JSON Strings
- Use
json.dumps()to convert Python objects to JSON strings. indentmakes output human-readable;sort_keys=Trueorders keys alphabetically.
import json
python_data = {
"deployment": "frontend-v2",
"replicas": 3,
"ports": [80, 443],
"health_check": True,
"logs_enabled": None
}
print(f"Simple JSON:\n{json.dumps(python_data)}")
print("\n")
print(f"Pretty JSON:\n{json.dumps(python_data, indent=2, sort_keys=True)}")
Serializing Python objects to JSON Files
- Use
json.dump()to write Python objects directly to files. - Pass the file handle and optional
indentfor formatting.
import json
from pathlib import Path
output = {
"status": "complete",
"items_processed": 1492,
"errors": []
}
output_path = Path("run_summary.json")
with output_path.open("w", encoding="utf-8") as file:
json.dump(output, file, indent=2)
(97)