Data Conversion Helper Functions in Python
A set of beginner-friendly helper functions to convert between JSON strings and Python data, parse dates, and read/write files using pathlib.
Python code
32 linesfrom datetime import datetime
from pathlib import Path
import json
def to_json(data, indent=2):
"""Convert Python data to pretty-printed JSON string."""
return json.dumps(data, indent=indent, default=str)
def from_json(json_string):
"""Parse JSON string back into Python data."""
return json.loads(json_string)
def to_datetime(date_str, fmt="%Y-%m-%d"):
"""Convert date string to datetime object."""
return datetime.strptime(date_str, fmt)
def read_file(file_path):
"""Read file content using pathlib."""
return Path(file_path).read_text(encoding="utf-8")
def write_file(file_path, content):
"""Write content to file using pathlib."""
Path(file_path).write_text(content, encoding="utf-8")
if __name__ == "__main__":
sample = {"name": "Ada", "born": "1815-12-10", "skills": ["math", "code"]}
json_data = to_json(sample)
print("JSON:", json_data)
print("Back:", from_json(json_data))
print("Date:", to_datetime("2024-01-15").date())
write_file("temp_output.txt", "Hello from converter!")
print("File:", read_file("temp_output.txt"))
Output
JSON: {
"name": "Ada",
"born": "1815-12-10",
"skills": [
"math",
"code"
]
}
Back: {'name': 'Ada', 'born': '1815-12-10', 'skills': ['math', 'code']}
Date: 2024-01-15
File: Hello from converter!
How it works
These helper functions leverage Python's standard library to simplify common data conversions. json.dumps with indent provides pretty-printed output, and default=str handles non-serializable types like datetime. datetime.strptime parses date strings according to the given format. Pathlib's read_text and write_text manage file I/O with explicit UTF-8 encoding. The main block demonstrates each function, showing conversion round-trips and file operations.
Common mistakes
- Forgetting to import modules like json, datetime, or pathlib.
- Passing a file object to json.loads instead of using json.load.
- Mismatching the date format string with the actual date string.
- Not handling file encoding explicitly, causing UnicodeDecodeError.
Variations
- Use json.load(file) to read JSON directly from a file object.
- Use dateutil.parser or pandas.to_datetime for flexible date parsing.
- Use pathlib.Path.open in a with block for large files.
Real-world use cases
- Serializing configuration dictionaries to JSON files for persistence.
- Parsing API response payloads into Python objects after HTTP requests.
- Converting user-input date strings to datetime for database inserts.
Sponsored
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
- How to Build a Wheel with Hatchling in Python easy
Keep learning
Related tutorials and quizzes for this topic.