Skip to content

Instantly share code, notes, and snippets.

@bnikanjam
Created January 22, 2023 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bnikanjam/aae6981ce4ffb62d10881cd4b318d7c4 to your computer and use it in GitHub Desktop.
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
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