-
-
Save j9t/6ecd1069a70462f7cd8853dcdbba4789 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
import json | |
import sys | |
from pathlib import Path | |
def sort_dict_recursively(d): | |
if isinstance(d, dict): | |
return {k: sort_dict_recursively(v) for k, v in sorted(d.items())} | |
elif isinstance(d, list): | |
return sorted(sort_dict_recursively(x) if isinstance(x, (dict, list)) else x for x in d) | |
return d | |
def sort_package_json(file_path): | |
with open(file_path, 'r') as f: | |
package_data = json.load(f) | |
sorted_data = sort_dict_recursively(package_data) | |
with open(file_path, 'w') as f: | |
json.dump(sorted_data, f, indent=2) | |
if __name__ == "__main__": | |
if len(sys.argv) != 2: | |
print("Usage: ./sort_package_json.py path/to/package.json") | |
sys.exit(1) | |
package_json_path = sys.argv[1] | |
if not Path(package_json_path).exists(): | |
print(f"Error: File {package_json_path} not found") | |
sys.exit(1) | |
sort_package_json(package_json_path) | |
print(f"Successfully sorted {package_json_path}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python script to sort package.json contents alphabetically.
Usage:
chmod +x sort-package.json.py
./sort-package.json.py path/to/package.json