json_utils.py 817 B

123456789101112131415161718192021
  1. import json
  2. def write_json(data, file_path, indent=None, ensure_ascii=False):
  3. """
  4. Centralized function to write Python objects to a JSON file.
  5. Args:
  6. data: The Python object (e.g., dict, list) to serialize.
  7. file_path: The path to the output file.
  8. indent: The indentation level for pretty-printing. Defaults to None (compact).
  9. ensure_ascii: Whether to escape non-ASCII characters. Defaults to False.
  10. """
  11. try:
  12. with open(file_path, 'w', encoding='utf-8') as f:
  13. json.dump(data, f, indent=indent, ensure_ascii=ensure_ascii)
  14. except IOError as e:
  15. print(f"Error writing JSON to {file_path}: {e}", file=sys.stderr)
  16. raise
  17. except TypeError as e:
  18. print(f"Error serializing data to JSON: {e}", file=sys.stderr)
  19. raise