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.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 12 views 0 copies

Python code

32 lines
Python 3.9+
from 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

stdout
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

  1. Use json.load(file) to read JSON directly from a file object.
  2. Use dateutil.parser or pandas.to_datetime for flexible date parsing.
  3. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.