Skip to content

Instantly share code, notes, and snippets.

@BoDonkey
Created March 12, 2025 12:44
Show Gist options
  • Save BoDonkey/36484f04255a4dede7816069128d4fda to your computer and use it in GitHub Desktop.
Save BoDonkey/36484f04255a4dede7816069128d4fda to your computer and use it in GitHub Desktop.
Node.js gist to alphabetize translation key:string value pairs in JSON files
const fs = require('fs');
const path = require('path');
/**
* Sorts the keys of a JSON object alphabetically and returns a new sorted object
*
* @param {Object} obj - The JSON object to sort
* @returns {Object} - A new object with sorted keys
*/
function sortObjectKeys(obj) {
// Get all keys and sort them alphabetically
const sortedKeys = Object.keys(obj).sort();
// Create a new object with sorted keys
const sortedObj = {};
for (const key of sortedKeys) {
sortedObj[key] = obj[key];
}
return sortedObj;
}
/**
* Sorts keys in a JSON file alphabetically
*
* @param {string} filePath - Path to the JSON file
* @param {boolean} createBackup - Whether to create a backup of the original file
* @returns {void}
*/
function sortJsonFile(filePath, createBackup = true) {
console.log(`Processing file: ${filePath}`);
try {
// Read the file
const content = fs.readFileSync(filePath, 'utf8');
// Parse JSON
const jsonData = JSON.parse(content);
// Create backup if requested
if (createBackup) {
const backupPath = `${filePath}.backup`;
fs.writeFileSync(backupPath, content, 'utf8');
console.log(`Backup created: ${backupPath}`);
}
// Sort the object
const sortedData = sortObjectKeys(jsonData);
// Write the sorted JSON back to the file
fs.writeFileSync(filePath, JSON.stringify(sortedData, null, 2), 'utf8');
console.log(`File sorted successfully: ${filePath}`);
// Count the keys
const keyCount = Object.keys(sortedData).length;
console.log(`Total keys: ${keyCount}`);
} catch (error) {
console.error(`Error processing file ${filePath}: ${error.message}`);
}
}
/**
* Processes all JSON files in a directory
*
* @param {string} directoryPath - Path to the directory containing JSON files
* @param {boolean} createBackup - Whether to create backups of original files
* @returns {void}
*/
function processDirectory(directoryPath, createBackup = true) {
console.log(`Processing directory: ${directoryPath}`);
try {
// Get all files in the directory
const files = fs.readdirSync(directoryPath)
.filter(file => file.endsWith('.json'));
console.log(`Found ${files.length} JSON files`);
// Process each file
for (const file of files) {
const filePath = path.join(directoryPath, file);
sortJsonFile(filePath, createBackup);
}
console.log('All files processed successfully!');
} catch (error) {
console.error(`Error processing directory ${directoryPath}: ${error.message}`);
}
}
// Command line handling
if (require.main === module) {
const args = process.argv.slice(2);
if (args.length === 0) {
console.log('Usage:');
console.log(' For a single file: node sort-json-keys.js path/to/file.json [create-backup]');
console.log(' For a directory: node sort-json-keys.js path/to/directory [create-backup]');
console.log('');
console.log(' create-backup: true or false (default: true)');
process.exit(1);
}
const path = args[0];
const createBackup = args.length > 1 ? args[1].toLowerCase() === 'true' : true;
// Check if the path is a file or directory
if (fs.existsSync(path)) {
const stats = fs.statSync(path);
if (stats.isFile()) {
sortJsonFile(path, createBackup);
} else if (stats.isDirectory()) {
processDirectory(path, createBackup);
} else {
console.error(`${path} is neither a file nor a directory`);
}
} else {
console.error(`Path not found: ${path}`);
}
}
// Export functions for use in other scripts
module.exports = {
sortObjectKeys,
sortJsonFile,
processDirectory
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment