Created
January 22, 2023 02:13
-
-
Save bnikanjam/aae6981ce4ffb62d10881cd4b318d7c4 to your computer and use it in GitHub Desktop.
Format all json files from in the current path and all sub-directories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import json | |
def format_json_file(file_path): | |
# Open the JSON file | |
try: | |
with open(file_path, "r") as json_file: | |
# Load the JSON data from the file | |
json_data = json.load(json_file) | |
# Format the JSON data | |
json_data = json.dumps(json_data, indent=2) | |
# Write the formatted JSON data back to the file | |
with open(file_path, "w") as json_file: | |
json_file.write(json_data) | |
print(f"Formatted {file_path}") | |
except json.decoder.JSONDecodeError as e: | |
print(f"Invalid JSON in file {file_path}: {e}") | |
except FileNotFoundError as e: | |
print(f"File not found: {e}") | |
def get_json_files(directory): | |
json_files = [] | |
for root, dirs, files in os.walk(directory): | |
json_files.extend( | |
os.path.join(root, file) for file in files if file.endswith(".json") | |
) | |
return json_files | |
if __name__ == "__main__": | |
json_files = get_json_files(os.getcwd()) | |
for file in json_files: | |
format_json_file(file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment