|
1 | 1 | import json
|
| 2 | +import argparse |
| 3 | +import sys |
2 | 4 |
|
3 | 5 |
|
4 | 6 | def format_php_array(data, indent=0):
|
@@ -38,9 +40,31 @@ def format_php_value(value, indent):
|
38 | 40 | return str(value)
|
39 | 41 |
|
40 | 42 |
|
| 43 | +def parse_arguments(): |
| 44 | + parser = argparse.ArgumentParser(description="Convert JSON to PHP array.") |
| 45 | + parser.add_argument("input_file", nargs='?', default="./input.json", |
| 46 | + help="Path to the input JSON file. Default is './input.json'") |
| 47 | + parser.add_argument("output_file", nargs='?', default=None, |
| 48 | + help="Path to the output PHP file. If not provided, output will be printed to console.") |
| 49 | + |
| 50 | + return parser.parse_args() |
| 51 | + |
| 52 | + |
41 | 53 | if __name__ == "__main__":
|
42 |
| - json_data = json.load(open("./input.json", "r")) |
| 54 | + args = parse_arguments() |
| 55 | + |
| 56 | + try: |
| 57 | + with open(args.input_file, "r") as file: |
| 58 | + json_data = json.load(file) |
| 59 | + except FileNotFoundError: |
| 60 | + sys.exit(f"Error: The file '{args.input_file}' does not exist.") |
| 61 | + except json.JSONDecodeError: |
| 62 | + sys.exit(f"Error: The file '{args.input_file}' contains invalid JSON.") |
43 | 63 |
|
44 |
| - # 格式化PHP数组 |
45 | 64 | formatted_php_array = format_php_array(json_data)
|
46 |
| - print("<?php\n$myArray = " + formatted_php_array + ";\n?>") |
| 65 | + |
| 66 | + if args.output_file: |
| 67 | + with open(args.output_file, "w") as output_file: |
| 68 | + output_file.write("<?php\n$myArray = " + formatted_php_array + ";\n?>") |
| 69 | + else: |
| 70 | + print("<?php\n$myArray = " + formatted_php_array + ";\n?>") |
0 commit comments