123456789101112131415161718192021 |
- import json
- def write_json(data, file_path, indent=None, ensure_ascii=False):
- """
- Centralized function to write Python objects to a JSON file.
- Args:
- data: The Python object (e.g., dict, list) to serialize.
- file_path: The path to the output file.
- indent: The indentation level for pretty-printing. Defaults to None (compact).
- ensure_ascii: Whether to escape non-ASCII characters. Defaults to False.
- """
- try:
- with open(file_path, 'w', encoding='utf-8') as f:
- json.dump(data, f, indent=indent, ensure_ascii=ensure_ascii)
- except IOError as e:
- print(f"Error writing JSON to {file_path}: {e}", file=sys.stderr)
- raise
- except TypeError as e:
- print(f"Error serializing data to JSON: {e}", file=sys.stderr)
- raise
|