Python JSON Data Handling Example
Description
This Python snippet provides essential functions for handling JSON (JavaScript Object Notation) data. It demonstrates how to parse a JSON string into a Python dictionary using `json.loads()` and how to serialize a Python dictionary back into a human-readable JSON string using `json.dumps()` with indentation. It includes basic error handling for robust data processing.
Code Snippet
import json
def parse_json_data(json_string):
"""
Parses a JSON string into a Python dictionary.
Args:
json_string (str): The JSON data as a string.
Returns:
dict: A Python dictionary representation of the JSON data.
Returns None if parsing fails.
"""
try:
data = json.loads(json_string)
return data
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
return None
def serialize_python_data(data_dict):
"""
Serializes a Python dictionary into a formatted JSON string.
Args:
data_dict (dict): The Python dictionary to serialize.
Returns:
str: A pretty-printed JSON string.
"""
try:
json_output = json.dumps(data_dict, indent=4)
return json_output
except TypeError as e:
print(f"Error serializing data: {e}")
return None
# --- Example Usage ---
# 1. Parsing a JSON string
json_str = '{"name": "Alice", "age": 30, "city": "New York"}'
parsed_data = parse_json_data(json_str)
if parsed_data:
print("Parsed JSON:", parsed_data)
print(f"Name: {parsed_data.get('name')}")
# 2. Serializing Python data to JSON
python_dict = {
"product": "Laptop",
"price": 1200,
"features": ["lightweight", "fast_processor", "long_battery_life"],
"available": True
}
json_output_str = serialize_python_data(python_dict)
if json_output_str:
print("\nSerialized JSON:\n", json_output_str)