Advanced JSON Handling
Custom JSON Encoding
Creating Custom JSON Encoders
class CustomJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)
## Usage
data = {"timestamp": datetime.now()}
json_string = json.dumps(data, cls=CustomJSONEncoder)
JSON Schema Validation
Using jsonschema Library
from jsonschema import validate
## Define JSON Schema
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer", "minimum": 0}
},
"required": ["name"]
}
## Validate JSON
try:
validate(instance={"name": "LabEx", "age": 25}, schema=schema)
except jsonschema.exceptions.ValidationError as e:
print(f"Validation Error: {e}")
Complex JSON Manipulation
Nested JSON Handling
def deep_get(data, *keys):
for key in keys:
try:
data = data[key]
except (KeyError, TypeError):
return None
return data
## Example usage
complex_json = {
"user": {
"profile": {
"details": {
"email": "[email protected]"
}
}
}
}
email = deep_get(complex_json, "user", "profile", "details", "email")
graph TD
A[JSON Performance] --> B[Streaming Parsing]
A --> C[Incremental Processing]
A --> D[Memory Efficient Methods]
Large File Handling
def json_stream_parser(filename):
with open(filename, 'r') as file:
for line in file:
try:
yield json.loads(line)
except json.JSONDecodeError:
continue
## Usage
for item in json_stream_parser('large_data.json'):
process_item(item)
Technique |
Description |
Use Case |
Flattening |
Convert nested JSON to flat structure |
Data normalization |
Merging |
Combine multiple JSON objects |
Data aggregation |
Filtering |
Remove specific keys/values |
Data cleaning |
Handling Special Data Types
import decimal
import uuid
class AdvancedJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return float(obj)
if isinstance(obj, uuid.UUID):
return str(obj)
return super().default(obj)
Error Handling Strategies
graph TD
A[JSON Error Handling] --> B[Catch Specific Exceptions]
A --> C[Provide Fallback Mechanisms]
A --> D[Log Detailed Error Information]
Robust Parsing Approach
def safe_json_load(data, default=None):
try:
return json.loads(data)
except (json.JSONDecodeError, TypeError):
return default or {}
Best Practices
- Use type hints for JSON structures
- Implement comprehensive error handling
- Consider performance for large datasets
- Validate input before processing
By mastering these advanced JSON handling techniques, LabEx developers can create more robust and efficient data processing solutions in Python.