|
| 1 | +#!/usr/bin/env python |
| 2 | +import json |
| 3 | +import argparse |
| 4 | + |
| 5 | +# Error codes |
| 6 | +JSON_ERROR_OK = 0 |
| 7 | +JSON_ERROR_OPENFILE = 1 |
| 8 | +JSON_ERROR_PARSE = 2 |
| 9 | +JSON_ERROR_COMPACTFILE = 3 |
| 10 | +JSON_ERROR_WRITEFILE = 4 |
| 11 | + |
| 12 | +# Error messages |
| 13 | +error_messages = { |
| 14 | + JSON_ERROR_OK: "Success", |
| 15 | + JSON_ERROR_OPENFILE: "Failed to open input file", |
| 16 | + JSON_ERROR_PARSE: "Failed to parse JSON", |
| 17 | + JSON_ERROR_COMPACTFILE: "Failed to compact JSON", |
| 18 | + JSON_ERROR_WRITEFILE: "Failed to write output file" |
| 19 | +} |
| 20 | + |
| 21 | +def ladder_compact_json_file(input_path, output_path): |
| 22 | + """ |
| 23 | + Compact a JSON file by removing unnecessary whitespace. |
| 24 | + |
| 25 | + Args: |
| 26 | + input_path (str): Path to the input JSON file. |
| 27 | + output_path (str): Path to the output compacted JSON file. |
| 28 | + |
| 29 | + Returns: |
| 30 | + int: Error code indicating success or type of failure. |
| 31 | + """ |
| 32 | + try: |
| 33 | + with open(input_path, 'r') as f: |
| 34 | + data = json.load(f) |
| 35 | + except FileNotFoundError: |
| 36 | + return JSON_ERROR_OPENFILE |
| 37 | + except json.JSONDecodeError: |
| 38 | + return JSON_ERROR_PARSE |
| 39 | + |
| 40 | + try: |
| 41 | + compact_json = json.dumps(data, separators=(',', ':')) |
| 42 | + except Exception: |
| 43 | + return JSON_ERROR_COMPACTFILE |
| 44 | + |
| 45 | + try: |
| 46 | + with open(output_path, 'w') as f: |
| 47 | + f.write(compact_json) |
| 48 | + except Exception: |
| 49 | + return JSON_ERROR_WRITEFILE |
| 50 | + |
| 51 | + return JSON_ERROR_OK |
| 52 | + |
| 53 | +def main(): |
| 54 | + parser = argparse.ArgumentParser(description="Compact a JSON file by removing unnecessary whitespace.") |
| 55 | + parser.add_argument("input", help="Path to the input JSON file") |
| 56 | + parser.add_argument("output", help="Path to the output compacted JSON file") |
| 57 | + args = parser.parse_args() |
| 58 | + |
| 59 | + result = ladder_compact_json_file(args.input, args.output) |
| 60 | + if result == JSON_ERROR_OK: |
| 61 | + print("JSON compacted successfully.") |
| 62 | + else: |
| 63 | + print(f"Error: {error_messages.get(result, 'Unknown error')}") |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + main() |
0 commit comments