Here are 10 Python code snippets demonstrating Handling JSON Data using Python's json module. These examples cover parsing JSON data and creating JSON data.
Reading JSON data from a file and converting it into a Python dictionary.
4. Writing JSON to a File
Writing a Python dictionary to a JSON file.
5. Pretty-Printing JSON Data
Formatting JSON data for readability with indentation.
6. Converting Python Lists to JSON
Converting a Python list to a JSON-formatted string.
7. Handling Non-ASCII Characters in JSON
Ensuring non-ASCII characters are properly handled when converting to JSON.
8. Customizing JSON Serialization
Customizing the way objects are serialized by using a custom default function.
9. Handling JSON with Nested Structures
Parsing and working with JSON data that contains nested structures.
10. Deserializing JSON with Custom Classes
Converting JSON data into custom Python objects by subclassing json.JSONDecoder.
These snippets show how to handle JSON data in Python, including parsing, creating, reading, and writing JSON. The examples also cover customization options for handling non-ASCII characters, nested structures, and more complex serialization and deserialization scenarios.
import json
from datetime import datetime
def default_serializer(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Type {type(obj)} not serializable")
data = {"event": datetime(2024, 8, 1, 14, 30)}
json_string = json.dumps(data, default=default_serializer)
print(json_string) # Output: {"event": "2024-08-01T14:30:00"}
import json
json_string = '{"name": "Eve", "address": {"city": "New York", "zip": "10001"}}'
data = json.loads(json_string)
print(data['address']['city']) # Output: New York
import json
class CustomDecoder(json.JSONDecoder):
def decode(self, s, **kwargs):
data = super().decode(s, **kwargs)
data['name'] = data['name'].upper() # Modify the 'name' field
return data
json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string, cls=CustomDecoder)
print(data) # Output: {'name': 'ALICE', 'age': 30}