Advertisement
Python253

json_to_text

Mar 14th, 2024
570
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.31 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: json_to_text.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts a JSON file (.json) to a text file (.txt).
  10. It reads the JSON file, pretty-prints its content, and saves it as a text file.
  11. The output text file is formatted with indentation for better readability.
  12.  
  13. Requirements:
  14. - Python 3.x
  15.  
  16. Usage:
  17. 1. Save this script as 'json_to_text.py'.
  18. 2. Ensure your JSON file ('example.json') is in the same directory as the script.
  19. 3. Run the script.
  20.  
  21. Note: Adjust the 'input_json_file' and 'output_text_file' variables in the script as needed.
  22. """
  23. import json
  24. import os
  25.  
  26. def json_to_text(input_json_file, output_text_file):
  27.     input_json_path = os.path.join(os.getcwd(), input_json_file)
  28.     output_text_path = os.path.join(os.getcwd(), output_text_file)
  29.  
  30.     with open(input_json_path, 'r', encoding='utf-8') as json_file:
  31.         data = json.load(json_file)
  32.  
  33.     with open(output_text_path, 'w', encoding='utf-8') as text_file:
  34.         text_file.write(json.dumps(data, indent=2, ensure_ascii=False))
  35.  
  36. if __name__ == "__main__":
  37.     input_json_file = 'example.json'
  38.     output_text_file = 'json2txt.txt'
  39.     json_to_text(input_json_file, output_text_file)
  40.     print(f"Converted '{input_json_file}' to '{output_text_file}'.")
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement