Advertisement
Python253

bin2json

Mar 11th, 2024
664
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.26 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: bin2json.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts a binary file (.bin) to a JSON file (.json).
  10. It reads the binary content, assuming each line in the binary file represents a separate record.
  11. The script decodes each line from UTF-8 and saves the data as a JSON file with a "binary_content" key.
  12.  
  13. Requirements:
  14. - Python 3.x
  15.  
  16. Usage:
  17. 1. Save this script as 'bin2json.py'.
  18. 2. Ensure your binary file ('example.bin') is in the same directory as the script.
  19. 3. Run the script.
  20. 4. The converted JSON file ('bin2json.json') will be generated in the same directory.
  21.  
  22. Note: Adjust the 'bin_filename' and 'json_filename' variables in the script as needed.
  23. """
  24.  
  25. import json
  26.  
  27. def bin_to_json(bin_filename, json_filename):
  28.  data = {"binary_content": []}
  29.  with open(bin_filename, 'rb') as binfile:
  30.      for line in binfile:
  31.          data["binary_content"].append(line.decode('utf-8').strip())
  32.  
  33.  with open(json_filename, 'w') as jsonfile:
  34.      json.dump(data, jsonfile, indent=2)
  35.  
  36. if __name__ == "__main__":
  37.  bin_filename = 'example.bin'
  38.  json_filename = 'bin2json.json'
  39.  bin_to_json(bin_filename, json_filename)
  40.  print(f"Converted '{bin_filename}' to '{json_filename}'.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement