2023-07-06 09:36:57 +00:00
|
|
|
import argparse
|
|
|
|
import json
|
|
|
|
from pathlib import Path
|
|
|
|
|
2024-12-19 12:48:57 +00:00
|
|
|
|
2023-07-06 09:36:57 +00:00
|
|
|
def indent_json_file(input_file, output_file=None, indent=4):
|
|
|
|
# Read the JSON file
|
2024-12-19 12:48:57 +00:00
|
|
|
with open(input_file, "r") as file:
|
2023-07-06 09:36:57 +00:00
|
|
|
data = json.load(file)
|
|
|
|
|
|
|
|
# Determine the output file path
|
|
|
|
if output_file is None:
|
2024-12-19 12:48:57 +00:00
|
|
|
output_file = input_file.with_stem(
|
|
|
|
input_file.stem + "_indented" + input_file.suffix
|
|
|
|
)
|
2023-07-06 09:36:57 +00:00
|
|
|
|
|
|
|
# Write the indented JSON to the output file
|
2024-12-19 12:48:57 +00:00
|
|
|
with open(output_file, "w") as file:
|
2023-07-06 09:36:57 +00:00
|
|
|
json.dump(data, file, indent=indent)
|
|
|
|
|
2024-12-19 12:48:57 +00:00
|
|
|
|
2023-07-06 09:36:57 +00:00
|
|
|
def main():
|
2024-12-19 12:48:57 +00:00
|
|
|
parser = argparse.ArgumentParser(
|
|
|
|
description="Indent a JSON file and save it to a new file."
|
|
|
|
)
|
|
|
|
parser.add_argument("input_file", type=Path, help="path to the input JSON file")
|
|
|
|
parser.add_argument(
|
|
|
|
"-o", "--output_file", type=Path, help="path to the output JSON file"
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"--indent",
|
|
|
|
type=int,
|
|
|
|
default=4,
|
|
|
|
help="number of spaces for indentation (default: 4)",
|
|
|
|
)
|
2023-07-06 09:36:57 +00:00
|
|
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
input_file = args.input_file
|
|
|
|
output_file = args.output_file
|
|
|
|
indent = args.indent
|
|
|
|
|
|
|
|
indent_json_file(input_file, output_file, indent)
|
|
|
|
|
2024-12-19 12:48:57 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2023-07-06 09:36:57 +00:00
|
|
|
main()
|