Created
February 10, 2024 09:44
-
-
Save glowinthedark/500ed69c83584c8510d5d60d8220ced0 to your computer and use it in GitHub Desktop.
remove empty or null keys from JSON file; print to stdout or to file with `-o output.json`; to beautify output JSON add the `-f` flag
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 node | |
const fs = require('fs'); | |
// Function to remove null keys from an object | |
function removeEmpty(obj) { | |
Object.keys(obj).forEach(function(key) { | |
if (obj[key] && typeof obj[key] === 'object') { | |
removeEmpty(obj[key]); | |
} else if (obj[key] === '' || obj[key] === null) { | |
delete obj[key]; | |
} | |
}); | |
return obj; | |
} | |
// Read the input file path from command line arguments | |
const inputFile = process.argv[2]; // Corrected this line | |
if (!inputFile) { | |
console.error('Usage: node script.js <input-file> [-o output.json]'); | |
process.exit(1); | |
} | |
// Read the JSON data from the input file | |
try { | |
const jsonData = JSON.parse(fs.readFileSync(inputFile, 'utf8')); | |
const cleanedData = removeEmpty(jsonData); | |
// Check if the -o flag is provided for output file | |
const outputFileIndex = process.argv.indexOf('-o'); | |
if (outputFileIndex !== -1 && process.argv[outputFileIndex + 1]) { | |
const outputFileName = process.argv[outputFileIndex + 1]; | |
fs.writeFileSync(outputFileName, JSON.stringify(cleanedData, null, process.argv.includes('-f') ? 2 : 0)); | |
console.log(`Result written to ${outputFileName}`); | |
} else { | |
console.log(JSON.stringify(cleanedData, null, process.argv.includes('-f') ? 2 : 0)); | |
} | |
} catch (error) { | |
console.error('Error reading or processing the input file:', error.message); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment